I've implemented a C++ Class that will execute something in a timed cycle using a thread. The thread is set to be scheduled with the SCHED_DEADLINE scheduler of the Linux kernel. To setup the Scheduler the process running this must have certain Linux capabilities.
My question is, how to test this?
I can of course make a unit test and create the threat, do some counting an exit the test after a time to validate the cycle counter but that only works if the unit test is allowed to apply the right scheduler. If not, the default scheduler applies and the timing of the cyclic loops will be immediate and therefore executes a different behaviour.
How would you test this scenario?
Some Code Example:
void thread_handler() {
// setup SCHED_DEADLINE Parameters
while (running) {
// execute application logic
sched_yield();
}
}
There two separate units to test here. First the cyclic execution of code and second the strategy with the os interface. The first unit would look like this:
class CyclicThread : public std::thread {
public:
CyclicThread(Strategy& strategy) :
std::thread(bind(&CyclicThread::worker, this)),
strategy(strategy) { }
add_task(std::function<void()> handler) {
...
}
private:
Strategy& strategy;
void worker() {
while (running) {
execute_handler()
strategy.yield();
}
}
}
This is fairly easy to test with a mock object of the strategy.
The Deadline scheduling strategy looks like this:
class DeadlineStrategy {
public:
void yield() {
sched_yield();
}
}
This class can also be tested fairly easy by mocking the sched_yield() system call.
Related
In my event-driven application I have common issue. Suppose following class diagram:
I'm using observer pattern here. Worker and WorkerManager lives in the same thread. Now suppose sequence of actions:
Worker calls listener class to report result in the middle of method
WorkerManager (which is listener of Worker) decides to delete/modify Worker class
Worker continue execution of method, being removed of modified. Programmer must consider these situations, and it is complicated and error-prone.
In code it might look like that:
// in worker.cpp
void Worker::SomeMethod() {
...
listener_->OnWorkDone(this); // removed here by listener
workDone_ = true; // memory corruption
...
}
// in worker_manager.cpp
void WorkerManager::OnWorkerWorkDone(Worker* worker) {
RemoveWorker(worker);
}
How it can be modified:
// in worker.cpp
void Worker::DoSomeWork() {
workDone = false;
...
}
void Worker::SomeMethod() {
...
listener_->OnWorkDone(this); // sets workDone to false here by DoSomeWork()
workDone_ = true; // but SomeMethod doesn't aware of it
...
}
// in worker_manager.cpp
void WorkerManager::OnWorkerWorkDone(Worker* worker) {
worker->DoSomeWork(); // do another work
}
Now I see these solutions to problem:
Set by code style guide that listener class must be called last. But it quite fragile and error prone solution.
Made sort of QT queued connections.
QT queued connections is made on meta-object system and it is way too much for my project. I need a simpler tool that would allow me to defer listener callbacks in thread's event loop.
I believe that this issue is common in event-driven design. Where can I see examples of how it can be handled?
In what situation should we adopt state pattern?
I've been assigned to maintain a project, the project state machine was implemented by switch-case that are 2000+ lines long. It will be hard to expand function, so I would like to refactor it.
I'm surveying state design pattern, but I have some confusions.
A simple example:
1. Initial state "WAIT", wait user send download command
2. While user send download command, move to "CONNECT" state, connect to server
3. After connection is created, move to "DOWNLOADING" state, keep receive data from server
4. While the data download complete, move to "DISCONNECT", disconnect link with server
5. After disconnect, move to "WAIT" state, wait user send download command
A simple state machine pic
Method 1: Before I survey state pattern, I think a trivial method --- wrapper different state behavior in different function, use a function pointer array to point each state function, and change state by call function.
typedef enum {
WAIT,
CONNECT,
DOWNLOADING,
DISCONNECT
}state;
void (*statefunction[MAX_STATE])(void) =
{
WAITState,
CONNECTState,
DOWNLOADINGState,
DISCONNECTState
};
void WAITState(void)
{
//do wait behavior
//while receive download command
//statefunction[CONNECT]();
}
void CONNECTState(void)
{
//do connect behavior
//while connect complete
//statefunction[DOWNLOADING]();
}
void DOWNLOADINGState(void)
{
//do downloading behavior
//while download complete
//statefunction[DISCONNECT]();
}
void DISCONNECTState(void)
{
//do disconnect behavior
//while disconnect complete
//statefunction[WAIT]();
}
Method 2: The state pattern encapsulates different state and its behavior in different class (object-oriented state machine), uses polymorphism to implement different state behavior, and defines a common interface for all concrete states.
class State
{
public:
virtual void Handle(Context *pContext) = 0;
};
class Context
{
public:
Context(State *pState) : m_pState(pState){}
void Request()
{
if (m_pState)
{
m_pState->Handle(this);
}
}
private:
State *m_pState;
};
class WAIT : public State
{
public:
virtual void Handle(Context *pContext)
{
//do wait behavior
}
};
class CONNECT : public State
{
public:
virtual void Handle(Context *pContext)
{
//do connect behavior
}
};
class DOWNLOADING : public State
{
public:
virtual void Handle(Context *pContext)
{
//do downloading behavior
}
};
class DISCONNECT : public State
{
public:
virtual void Handle(Context *pContext)
{
//do disconnect behavior
}
};
I'm wondering whether the state pattern batter than function pointer in this case or not...
Using function pointer only also can improve readability (compare with switch-case), and more simple.
The state pattern will create several class, and more complex than using function pointer only.
What's the advantage of using state pattern?
Thanks for your time!
What's the advantage of using the state pattern?
First, one needs to notice, that both of the methods you've provided, are in fact examples of the very same pattern. One of the methods describes a function-based implementation, while the other one takes more of an object oriented approach.
That being said, the pattern itself has a few advantages:
It limits the number of states, a program can be in, and thus - eliminates undefined states,
It allows for easier expansion of the application, by adding new states, instead of refactoring the whole code,
From a company perspective, it is safe, even when multiple people work on the same class,
Since you tagged the question as related to c++, it is best to take into account what the language both gives and requires. While classes offer inheritance, a large number of classes can greatly increase the compilation time. Hence, when it comes to implementations, if your state machine is large, static polymorphism may be the way to go.
I'm trying to work out a design predicament I have.
ClassWithLongOperation
{
Run()
{
RecrusiveOperation();
}
RecrusiveOperation()
{
/* RECURSION */
}
}
MyThread
{
ClassWithLongOperation Op1(10);
Op1.Run(); // Takes several minutes.
ClassWithLongOperation Op2(20);
Op2.Run();
SomeOtherClassWithLongOperation Op3;
Op3.Run();
// Do some other stuff
}
The GUI starts MyThread, which runs for a good 5-6 minutes. I want to be able to have a big fat Cancel button on my GUI, so the user can cancel the operation.
I could create a global boolean variable bCancelled, and check if its been set in RecursiveOperation, but I want to be a good C++ & OO programmer and avoid global variables. Especially if they would have to spread across multiple files.
So how would I (following good design) safely cancel MyThread? What could I change in my setup to allow this?
I'm also using _beginthreadex to start the thread, but I could use boost if it would allow for an easier solution.
Your flag not need to be global to your entire program, but it needs to be visible to your class code. Create the flag to be a private instance member and a public function to change it to false/true. In your recursive function, test its value to verify if the task should continue. When you want, set its value to false (through the function of course) to stop the recursive calls, i.e., when the user clicks the button you call the function in the desired instance. This way you will not break any OO principle, since you have a private flag and a public member function to safely change it.
Using a global variable is actually not the worst thing in the world. Having a proliferation of unnecessary global variables leads to maintenance nightmares, but it actually sounds like a quick and easy-to-understand solution here. But if you want a clean OO solution, this is certainly possible:
EDIT My original post overlooked the fact that you want to be able to run several operations in sequence, and if any of them is cancelled, none of the remaining operations are performed. This means it's more useful to keep the bool flag inside the canceller, instead of separately in each cancellable operation; and exceptions are the nicest way to handle the actual control flow. I've also tightened up a few things (added volatile for the flag itself, made names clearer, restricted unnecessary access rights).
// A thing that can cancel another thing by setting a bool to true.
class Canceller {
public:
Canceller : cancelledFlag(false) {}
void RegisterCancellee(Cancellee const& c) {
c.RegisterCanceller(cancelledFlag);
}
void Cancel() {
cancelledFlag = true;
}
private:
volatile bool cancelledFlag;
};
class CancelButton : public Canceller {
...
// Call Cancel() from on-click event handler
...
};
class Cancellation : public std::exception {
public:
virtual const char* what() const throw() {
return "User cancelled operation";
}
};
// A thing that can be cancelled by something else.
class Cancellee {
friend class Canceller; // Give them access to RegisterCanceller()
protected:
Cancellee() : pCancelledFlag(0) {}
// Does nothing if unconnected
void CheckForCancellation() {
if (pCancelledFlag && *pCancelledFlag) throw Cancellation();
}
private:
void RegisterCanceller(volatile bool& cancelledFlag) {
pCancelledFlag = &cancelledFlag;
}
volatile bool* pCancelledFlag;
};
class Op1 : public Cancellee { // (And similarly for Op2 and Op3)
...
// Poll CheckForCancellation() inside main working loop
...
};
MyThread
{
CancelButton cancelButton("CANCEL!");
try {
ClassWithLongOperation Op1(10);
cancelButton.RegisterCancellee(Op1);
Op1.Run(); // Takes several minutes.
ClassWithLongOperation Op2(20);
cancelButton.RegisterCancellee(Op2);
Op2.Run();
SomeOtherClassWithLongOperation Op3;
cancelButton.RegisterCancellee(Op3);
Op3.Run();
} catch (Cancellation& c) {
// Maybe write to a log file
}
// Do some other stuff
}
The "double bouncing" registration allows the canceller to give access to a private flag variable.
The most important thing is to not use thread termination functions, except in very specialised cases. Why? They don't run destructors. Nor do they give the target thread any chance to "clean up".
Instead of using a global variable, add a method to ClassWithLongOperation and/or MyThread, something like cancelOperation() that will set an internal boolean variable. The appropriate class methods would then need to check the variable at appropriate moments.
You could implement a Stop() method for your ClassWithLongOperation and have the event handler for BigFatCancelButton to call this Stop() method for the current operation.
... Or add a Stop() method to the Thread class and make the work objects be aware of the threads they're running in. You may as well throw in a Stop() method for the work objects. Depending on what's more important: Stop the thread or the work object.
I wrote an unit test using the gwt-test-utils framework, as described here.
The tested class internally uses a com.google.gwt.user.client.Timer (not the Java default Timer).
Only when tested, though, the Timer instance doesn't behave correctly, as it fires as soon as it is scheduled.
When I run this test
public class TimerTest extends GwtTest {
#Override
public String getModuleName() {
return "com.whatevs";
}
#Test
public void testTimer() {
final int[] counter = { 0 };
com.google.gwt.user.client.Timer t = new Timer() {
#Override
public void run() {
Log.info("firing timer");
counter[0]++; // just increase the counter
}
};
Log.info("scheduling timer");
t.schedule(1000000); // this should return immediately
Log.info("scheduling returns");
assertEquals(0, counter[0]); // the counter shouldn't yet be incremented
}
}
I get a failure
testTimer(com.whatevs.TimerTest): expected:<0> but was:<1>
And the debug output
22:37:44,075 INFO gwt-log:81 - scheduling timer
22:37:44,075 INFO gwt-log:81 - firing timer
22:37:44,075 INFO gwt-log:81 - scheduling returns
Please note that the test is run as a JUnit test, without being compiled to JavaScript first.
Am I doing something wrong, or did I just hit a bug?
Is there any other way to test such classes?
Update:
I just found out that if in the above example i call scheduleRepeating, or I reschedule the timer using schedule inside the run method, the timer fires exactly 5 times before returning control to the caller.
Something weird is going on, I just opened a bug report on gwt-test-utils.
Our business has recently moved to a TDD style and I'm new at writing unit tests. The C# (.net 3.5) piece I'm writing now should be able to verify a separate process is running, as I understand it the best way using the Mutex class.
So I have a method in my SrsUpdaterController class like so...
public bool IsUpdaterRunning()
{
Mutex srsUpdaterMutex = new Mutex(false, SRS_UPDATERGUID);
if (srsUpdaterMutex.WaitOne(0)) //If SRS Updater is running
{
srsUpdaterMutex.ReleaseMutex();
srsUpdaterMutex.Close();
return false;
}
else
{
return true;
}
}
and I have a test
[TestMethod()]
public void IsUpdaterRunningTrueTest()
{
SrsUpdaterController target = new SrsUpdaterController();
string mutexGuid = SrsUpdaterController.SRS_UPDATERGUID;
bool expected = true;
bool actual;
Mutex srsUpdaterMutex = new Mutex(false, mutexGuid);
srsUpdaterMutex.WaitOne(3000);
actual = target.IsUpdaterRunning();
srsUpdaterMutex.ReleaseMutex();
srsUpdaterMutex.Close();
Assert.AreEqual(expected, actual);
}
It doesn't work because the unit test and the IsUpdaterRunning method are called by the same thread, and so Windows is "smart" enough to not make the process block its self. The problem is I WANT the process to block its self so that it simulates the mutex being claimed. Is there any way to do this? Or am I approaching unit testing/process synchronization/mutex management all wrong?
(note, I did also try locking the Mutex on a separate thread launched from the test, but it still allowed me to claim the mutex in both places. Which is ok because I'd rather avoid threads when possible)
Thanks in advance!