Boost Statechart - Local transitions - c++

I'm hoping that someone can help me out with this problem, or at least point out the error of my ways...
As a simple illustration of my problem consider a part of an application where you can enter a "Functions Mode" state of operation. Four sub-modes are then available depending on which function key F1-F4 that the user presses. By default, F1 mode is entered. The state diagram starts off as follows:
The user can press F1-F4 at any time to switch to the corresponding mode. Adding these transitions to the inner states leads to the following:
Obviously this is (a) a mess, and (b) a lot of transitions to define. If at some point I want to add an F5Mode then... well, you get the picture. To avoid this I'd like to do the following:
Boost Statechart allows me to define transitions from FunctionMode to any of the inner states, but the result isn't what I expected. The actual outcome is as follows:
I.e. pressing F1-F4 to switch modes causes the outer FunctionMode state to be exited and re-entered along with triggering the unwanted exit and entry actions.
Way back in 2006, this thread between the library author and a user seems to describe the same problem. I think that the author suggests doing the following as a work-around:
However, that work-around doesn't seem very appealing to me: It has added an extra state level to be compiled, the code has become less readable, deep-history would have to be used to return to any of the function mode sub-states and the Intermediate state object is needlessly being destructed and constructed again.
So... where am I going wrong? Or what are the alternatives? I've had a brief look at Boost Meta State Machine (msm) but from what I've seen so far I much prefer the look of Statechart.
I'm surprised that more users haven't faced the same problem... which makes me think that perhaps my approach is completely wrong!

Have you looked at the in-state reaction explained in the statechart tutorial? It seems to be doing what you are looking for.
Since you are asking for alternatives, in this period I am evaluating various C++ Harel statechart implementations. I looked at Boost statechart and Boost MSM. I wrote code with both. They hurt my feeble brain :-)
Then I found Machine Objects (Macho), very simple and small, and I love it. It supports hierarchical state machines, entry/exit actions, history, state machine snapshots, guards, internal transitions, event deferring, state-local storage (with optional persistence), so to me it is a satisfying Harel statechart implementation.
This code implements the FunctionMode part of the statechart with Macho:
#include "Macho.hpp"
#include <exception>
#include <iostream>
using namespace std;
namespace FunctionMode {
struct FunctionMode;
struct F1Mode;
struct F2Mode;
// The Top state, containing all the others.
TOPSTATE(Top) {
STATE(Top)
// All the events of the state machine are just virtual functions.
// Here we throw to mean that no inner state has implemented the event
// handler and we consider that an error. This is optional, we could
// just have an empty body or log the error.
virtual void evF1() { throw std::exception(); }
virtual void evF2() { throw std::exception(); }
// evF3 and so on...
private:
void init() { setState<FunctionMode>(); } // initial transition
};
SUBSTATE(FunctionMode, Top) {
STATE(FunctionMode)
virtual void evF1() { setState<F1Mode>(); }
virtual void evF2() { setState<F2Mode>(); }
// evF3, ...
private:
void entry() { cout << "FunctionMode::entry" << endl; }
void exit() { cout << "FunctionMode::exit" << endl; }
void init() { setState<F1Mode>(); } // initial transition
};
SUBSTATE(F1Mode, FunctionMode) {
STATE(F1Mode)
virtual void evF1() {} // make the event an internal transition (by swallowing it)
private:
void entry() { cout << "F1Mode::entry" << endl; }
void exit() { cout << "F1Mode::exit" << endl; }
};
SUBSTATE(F2Mode, FunctionMode) {
STATE(F2Mode)
virtual void evF2() {} // make the event an internal transition (by swallowing it)
private:
void entry() { cout << "F2Mode::entry" << endl; }
void exit() { cout << "F2Mode::exit" << endl; }
};
} // namespace FunctionMode
int main() {
Macho::Machine<FunctionMode::Top> sm;
// Now the machine is already in F1Mode.
// Macho has 2 methods for synchronous event dispatching:
// First method:
sm->evF1(); // <= this one will be swallowed by F1Mode::evF1()
// Second method:
sm.dispatch(Event(&FunctionMode::Top::evF2));
return 0;
}
Running it, the output is:
FunctionMode::entry
F1Mode::entry
F1Mode::exit
F2Mode::entry
F2Mode::exit
FunctionMode::exit
that shows that the transitions are internal.
In my opinion, clean, easy and compact code :-)
[EDIT1] The first version of the code didn't perform the initial transition FunctionMode -> F1Mode. Now it does.

I know this is an old question, these exit->enter on the same state is annoying.
It seems that to prevent reentry to self you need to:
1. Write custom handler in "self state"
2. Write guards in the parent handler that triggers the reentry to child state.
Imho it is a flaw in StateChart that I haven't found a nice solution for yet - a property call "skip reentry state transitions" on the statemachine object would be great.

Related

Creating a C++ Event System

I've decided to begin making a game engine lately. I know most people don't finish theirs, and if I'm being honest I may not either. I'm doing this because I'm sick of googling "Cool C++ projects" and doing the 3 answers every single user gives (that'd be an address book or something similar, tic tac toe, and a report card generator or something like that). I like programming, but unfortunately I have no real use for it. Everything I would use it for I can do faster and easier in another way, or a solution already exists. However, in an effort to learn more than the basic level of C++ and do something that would teach me something that's truly in depth, I've revoked this policy and decided to begin a game engine, as it's something I've always been interested in. I've decided to model it loosely after Amazon's Lumberyard engine, as it's almost entirely C++ and gives me a good basis to learn from, as I can always just go there and do something with it to see how it behaves.
Onto the actual problem now:
I've got a working Entity Component system (yay), that although is in its early stages and not super great functionality wise, I'm very proud of. Honestly I never thought I'd get this far. I'm currently working with the Event Bus system. Now, I really love LY's EBus system. It's extremely easy to use and very straight forward, but from a programming newbie-ish's eyes it's black magic and witchcraft. I have no clue how they did certain things, so hopefully you do!
Making an EBus goes something like this:
#include <EBusThingy.h>
class NewEbusDealio
: public EbusThingy
{
public:
//Normally there's some setup work involved here, but I'm excluding it as I don't really feel that it's necessary for now. I can always add it later (see the footnote for details on what these actually are).
//As if by magic, this is all it takes to do it (I'd like to clarify that I'm aware that this is a pure virtual function, I just don't get how they generate so much usage out of this one line):
virtual void OnStuffHappening(arguments can go here if you so choose) = 0;
};
And that's it...
As if by magic, when you go to use it, all you have to do is this:
#include "NewEbusDealio.h"
class ComponentThatUsesTheBus
: public NewEbusDealio::Handler
{
public:
void Activate() override
{
NewEbusDealio::Handler::BusConnect();
}
protected:
void OnStuffHappening(arguments so chosen)
{
//Do whatever you want to happen when the event fires
}
};
class ComponentThatSendsEvents
{
public:
void UpdateOrWhatever()
{
NewEbusDealio::Broadcast(NewEbusDealio::Events::OnStuffHappening, arguments go here)
}
};
I just don't get how you can do this much stuff just by adding a single virtual function to NewEbusDealio. Any help on this is much appreciated. Sorry for so many text walls but I'd really like to get something out of this, and I've hit a massive brick wall on this bit. This may be way overkill for what I'm making, and it also may wind up being so much work that it's just not within the realm of possibility for one person to make in a reasonable amount of time, but if a simple version of this is possible I'd like to give it a go.
I'm putting this down here so people know what the setup work is. All you do is define a static const EBusHandlerPolicy and EBusAddressPolicy, which defines how many handlers can connect to each address on the bus, and whether the bus works on a single address (no address needed in event call), or whether you can use addresses to send events to handlers listening on a certain address. For now, I'd like to have a simple bus where if you send an event, all handlers receive it.
Not familiar with EBus you given, but event buses should be similar: one side creates an event and puts it into a list, the other side picks up events one by one and reacts.
As modern C++ gives us closure feature, it ismuch easier to implement a event bus now.
Following, I'm going to give a simple example, where looper is a event bus.
Be aware mutexs and conditional variables are necessary for this looper in production.
#include <queue>
#include <list>
#include <thread>
#include <functional>
class ThreadWrapper {
public:
ThreadWrapper() = default;
~ThreadWrapper() { Detach(); }
inline void Attach(std::thread &&th) noexcept {
Detach();
routine = std::forward<std::thread &&>(th);
}
inline void Detach() noexcept {
if (routine.joinable()) {
routine.join();
}
}
private:
std::thread routine{};
};
class Looper {
public:
// return ture to quit the loop, false to continue
typedef std::function<void()> Task;
typedef std::list<Task> MsgQueue;
Looper() = default;
~Looper() {
Deactivate();
}
// Post a method
void Post(const Task &tsk) noexcept {
Post(tsk, false);
}
// Post a method
void Post(const Task &tsk, bool flush) noexcept {
if(!running) {
return;
}
if (flush) msg_queue.clear();
msg_queue.push_back(tsk);
}
// Start looping
void Activate() noexcept {
if (running) {
return;
}
msg_queue.clear();
looping = true;
worker.Attach(std::thread{&Looper::Entry, this});
running = true;
}
// stop looping
void Deactivate() noexcept {
{
if(!running) {
return;
}
looping = false;
Post([] { ; }, true);
worker.Detach();
running = false;
}
}
bool IsActive() const noexcept { return running; }
private:
void Entry() noexcept {
Task tsk;
while (looping) {
//if(msg_queue.empty()) continue;
tsk = msg_queue.front();
msg_queue.pop_front();
tsk();
}
}
MsgQueue msg_queue{};
ThreadWrapper worker{};
volatile bool running{false};
volatile bool looping{false};
};
An example to use this Looper:
class MySpeaker: public Looper{
public:
// Call SayHi without blocking current thread
void SayHiAsync(const std::string &msg){
Post([this, msg] {
SayHi(msg);
});
}
private:
// SayHi will be called in the working thread
void SayHi() {
std::cout << msg << std::endl;
}
};

State Design Pattern - Don't want delete this pointer in member class

I am using the example below to implement a state design pattern.
https://sourcemaking.com/design_patterns/state/cpp/1
I don't wanna delete the *this pointer inside a member class because is not safe (I will call other member function after delete).
class ON: public State
{
public:
ON()
{
cout << " ON-ctor ";
};
~ON()
{
cout << " dtor-ON\n";
};
void off(Machine *m);
};
class OFF: public State
{
public:
OFF()
{
cout << " OFF-ctor ";
};
~OFF()
{
cout << " dtor-OFF\n";
};
void on(Machine *m)
{
cout << " going from OFF to ON";
m->setCurrent(new ON());
delete this; // <<< This line looks suspect and unsafe
}
};
void ON::off(Machine *m)
{
cout << " going from ON to OFF";
m->setCurrent(new OFF());
delete this; // <<< This line looks suspect and unsafe
}
Is there a better approach to implement the state design pattern? I thought about use Singletons, but I want avoid using singletons.
Best regards,
The design used in your link is:
a state machine keeps track of the pointer to the current state.
the current state is responsible to set the new state when a transition occcurs
it does so by creating the new state and instructing the machine to change the pointer
once this is done, the it comits suicide by deleteing itself.
As explained here, this can work if extra care is taken. Your code respects the prerequisites.
The alternative would be that the state machine deletes the current state in setCurrent(). But this is worse: as soon as the machine has deleted the object, this object no longer exists, so that when setCurrent() returns, you're de facto in the same (dangerous) situation as before (with delete this), with the important difference that this would not be obvious.
Edit:
If you feel unconfortable with this construct, you could opt for a variant:
class Machine
{
class State *current; // current state
class State *nextstate; // null, unless a state transition was requested
void check_transition(); // organise switch to nextstate if transition is needed
public:
Machine();
void setCurrent(State *s)
{
nextstate = s; // only sets the info about nextstate
}
void set_on();
void set_off();
};
In this scenario, the state-machine functions need to be slightly updated:
void Machine::set_on()
{
current->set_on(this); // as before
check_transition(); // organise the transition if the transition was requested
}
The state transition would then be managed by the state machine:
void Machine::check_transition() {
if (nextstate) {
swap (current, nextstate);
delete nextstate; // this contains the former current
nextstate = nullptr;
}
}
The machine organises the deletion of the unused states. Note that this approach would allow the use of shared_ptr instead of raw pointers.
Here a small online proof of concept.
By the way: the machine destructor should also delete the current and next state, in order to avoid leaking. And in any case the state destructor should be defined virtual
"... but I want avoid using singletons."
That's probably one of their rare valid use cases, since states should be stateless themselves (which doesn't mean they don't need an instance), and accessible concurrently regardless of the current state machine's context.
So that means you actually just need one instance of a state at a time.
The example shown at the mentioned website, also gives you an unnecessary performance hit, at the cost coming from new and delete whenever state changes, which could be avoided to have steady static instances for the states.
Actually you could consider to provide state instances as with the Flyweight Design Pattern, which essentially boils down to have Singleton state instances.
But well, it depends. UML state diagrams actually allow to have non-stateless states (as composite states with history attributes, or active states).
Have a look at my STTCL template library concept document, it explains some of the aspects, and design decisions I have used, to develop that template library, and how it can be used properly.
Be assured you I don't have any single delete this; in there ;-).
I'd say that example the website currently gives, is really badly designed and not generally recommendable1.
Using delete this isn't appropriate, dangerous and not acceptable, as you mentioned.
While using Singleton's is, if you have their valid use case at hand.
1) Sadly enough to notice this, since I've been using it as a "reference" for many design-patterns related questions here.

How can I do automata/state machine coding in C++?

I have used it in another programming language and It's very usefull.
I cannot find anything about this for C++.
Let's for example take the following code:
void change();
enum
{
end = 0,
gmx
}
int
gExitType;
int main()
{
gExitType = end;
SetTimer(&change, 10000, 0);
return 0;
}
void ApplicationExit()
{
switch (gExitType)
{
case end:
printf("This application was ended by the server");
case gmx:
printf("This application was ended by the timer");
}
::exit(0);
}
void change()
{
gExitType = gmx;
ApplicationExit();
}
That's kind of how we would do it in C++, but when using state machine/automata I could do something like this in the other language:
void change();
int main()
{
state exitType:end;
SetTimer(&change, 10000, 0);
return 0;
}
void ApplicationExit() <exitType:end>
{
printf("This application was ended by the server");
}
void ApplicationExit() <exitType:gmx>
{
printf("This application ended by the timer");
}
void change()
{
state exitType:gmx;
ApplicationExit();
}
In my opition this is a really elegant way to achieve things.
How would I do this in C++? This code doesn't seem to work (obviously as I cannot find anything automata related to C++)
To clarify my opinion:
So what are the advantages to using this technique? Well, as you can clearly see the code is smaller; granted I added an enum to the first version to make the examples more similar but the ApplicationExit functions are definately smaller. It's also alot more explicit - you don't need large switch statements in functions to determine what's going on, if you wanted you could put the different ApplicationExits in different files to handle different sets of code independently. It also uses less global variables.
There are C++ libraries like Boost.statechart that specifically try to provide rich support for encoding state machines:
http://www.boost.org/doc/libs/1_54_0/libs/statechart/doc/tutorial.html
Besides this, one very elegant way to encode certain types of state machines is by defining them as a couroutine:
http://c2.com/cgi/wiki?CoRoutine
http://eli.thegreenplace.net/2009/08/29/co-routines-as-an-alternative-to-state-machines/
Coroutines are not directly supported in C++, but there are two possible approaches for
implementing them:
1) Using a technique similar to implementing a duff's device, explained in details here:
http://blog.think-async.com/search/label/coroutines
This is very similar to how C#'s iterators work for example and one limitation is that yielding form the coroutine can be done only from the topmost function in the coroutine call-stack. OTOH, the advantage of this method is that very little memory is required for each instance of the coroutine.
2) Allocating a separate stack and registers space for each coroutine.
This essentially makes the coroutine a full-blown thread of execution with the only difference that the user has full responsibility for the thread scheduling (also known as cooperative multi-tasking).
A portable implementation is available from boost:
http://www.boost.org/doc/libs/1_54_0/libs/coroutine/doc/html/coroutine/intro.html
For this particular example, you could use objects and polymorphism to represent the different states. For example:
class StateObject
{
public:
virtual void action(void) = 0;
};
class EndedBy : public StateObject
{
private:
const char *const reason;
public:
EndedBy( const char *const reason_ ) : reason( reason_ ) { }
virtual void action(void)
{
puts(reason);
}
};
EndedBy EndedByServer("This application was ended by the server");
EndedBy EndedByTimer ("This application ended by the timer");
StateObject *state = &EndedByServer;
void change()
{
state = &EndedByTimer;
}
void ApplicationExit()
{
state->action();
::exit(0);
}
int main()
{
SetTimer(&change, 10000, 0);
// whatever stuff here...
// presumably eventually causes ApplicationExit() to get called before return 0;
return 0;
}
That said, this isn't great design, and it isn't an FSM in the general sense. But, it would implement your immediate need.
You might look up the State Pattern (one reference: http://en.wikipedia.org/wiki/State_pattern ) for a more general treatment of this pattern.
The basic idea, though, is that each state is a subclass of some common "state" class, and you can use polymorphism to determine the different actions and behaviors represented by each state. A pointer to the common "state" base class then keeps track of the state you're currently in.
The state objects may be different types, or as in my example above, different instances of the same object configured differently, or a blend.
You can use Template value specialization over an int to achieve pretty much what you want.
(Sorry I'm at my tablet so I cannot provide an example, I will update on Sunday)

Is there anything like timer and timertask in c++ just like java has?

I am not an experinced c++ programmer. So I just want to know how to implement timer and timertask just like java has in C++. I have tried timer_create example that is in man page of timer_create but It is not working as per my requirement.
I want that after particualar time span an event should fire, and if specific condition fulfills then timer should be canceled.
Any help would be highly appreciated.
Thanks,
Yuvi.
I too was looking for a Java like TimerTask but I needed one for Windows C++ when I came across this question. After a day of researching mostly on SO and learning about passing class member functions, I was able to put together a solution that seems to work well for me. I realize that I am years late in answering this question but maybe someone still looking for this solution will find this useful.
This is a Windows only solution which I tested on Windows 10 using Visual Studio C++. I'm still learning C++ so please be gentle if I've broken any rules. I realize the exceptions are elementary but they are easy to customize to your needs. I created a TimerTask class similar to the Java class. You'll need to derive a new user class from the TimerTask class and create a "task" function that includes the code you want executed at regular intervals. Here is the TimerTask class:
--TimerTask.h--
#pragma once
#include <thread>
class TimerTask {
HANDLE timeoutEvent;
DWORD msTimeout;
bool exit = false;
void* pObj;
static void taskWrapper(TimerTask* pObj) {
while (!pObj->exit) {
DWORD waitResult = WaitForSingleObject(pObj->timeoutEvent, pObj->msTimeout);
if (pObj->exit)
break;
pObj->task();
}
}
public:
TimerTask::TimerTask() {
timeoutEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (!timeoutEvent) {
throw "TimerTask CreateEvent Error: ";
}
}
TimerTask::~TimerTask() {
CloseHandle(timeoutEvent);
}
// Derived class must create task function that runs at every timer interval.
virtual void task() = 0;
void start(void* pObj, DWORD msTimeout) {
this->pObj = pObj;
this->msTimeout = msTimeout;
std::thread timerThread(taskWrapper, (TimerTask*)pObj);
timerThread.detach();
}
void stop() {
exit = true;
if (!SetEvent(timeoutEvent))
throw "TimerTask:stop(): Error: ";
}
};
And here is a sample of usage. For brevity I didn't include error checking.
--Test.cpp--
#include "Windows.h"
#include <iostream>
#include "TimerTask.h"
using namespace std;
class KeepAliveTask : public TimerTask {
public:
void task() {
cout << "Insert your code here!\n";
}
};
int main()
{
cout << "Hello, TimerTask!\n";
KeepAliveTask keepAlive;
keepAlive.start(&keepAlive, 1000); // Execute once per second
Sleep(5100); // Pause 5.1s to give time for task thread to run.
keepAlive.stop();
Sleep(1000); // Pause another sec to give time for thread to stop.
return 0;
}
This is generally a very difficult question, since you are inherently asking for some concurrent, or at least asynchronous processing.
The simplest, single-threaded solution is to use something like Posix's alarm(2). This will cause a signal to be sent to your process after a specified time. You need to register a signal handler (e.g. with signal(2)), but you are subject to all its limitations (e.g. you must only call async-safe functions within the handler).
A second, single-threaded option is to use a select-style (or epoll-style) I/O loop and use a kernel timer file descriptor. This is a very recent Linux feature, though, so availability will vary.
Finally, the typical, general solution is to use multiple threads: Make a dedicated thread for the timer whose only purpose is to sleep for the set time span and then execute some code. For this you will have to bear the full weight of concurrent programming responsibilities, such as handling shared data, guaranteeing the absence of races, etc.
Some higher-level libraries like Boost.ASIO and the new standard library provide some nice timing mechanisms once you've decided to go down the multithreaded route.

Handling mutual exclusion in C++11

I have a class representing a finite-state machine, which should run in a forever loop and check it's current state. In each state machine will set it's next state and either fall into idle state or do some work. I would like to allow another thread to change state of machine while it's working. This will cause a race condition as expected. So I add a mutual exclusion lock/unlock wrapping loop of machine and the public method that allows other threads to change current state of machine.
class Robot
{
public:
enum StateType {s1,s2,s3,idle,finish};
void run();
void move();
private:
StateType currentState;
StateType nextState;
StateType previousState;
std::mutex mutal_state;
};
Implementation:
void Robot::run()
{
this->currentState = s1;
while(true)
{
mutal_state.lock();
switch(currentState)
{
case s1:
// do some useful stuff here...
currentState = idle;
nextState = s3;
break;
case s2:
// do some other useful stuff here...
currentState = idle;
nextState = finish;
break;
case s3:
// again, do some useful things...
currentState = idle;
nextState = s2;
break;
case idle:
// busy waiting...
std::cout << "I'm waiting" << std::endl;
break;
case finish:
std::cout << "Bye" << std::endl;
mutal_state.unlock();
return;
}
mutal_state.unlock();
}
}
And the move method that allows other threads to change current state:
void Robot::move()
{
mutal_state.lock();
previousState = currentState; // Booommm
currentState = nextState;
mutal_state.unlock();
}
I can't manage to find what I'm doing wrong! Program crashes in first line of the move() function. On the other hand, the GDB is not working with C++11 and tracing code is not possible...
UPDATE:
Playing around code, I can see that problem is in move function. When the program tries to lock code piece inside move(), crashes. For example if move is like this:
void Robot::move()
{
std::cout << "MOVE IS CALLED" << std::endl;
mutal_state.lock();
//previousState = currentState;
//std::cout << "MOVING" << std::endl;
//currentState = nextState;
mutal_state.unlock();
}
Output is:
s1
I'm waiting
I'm waiting
MOVE IS CALLED1
The program has unexpectedly finished.
But when move is a simple function, not doing anything:
void Robot::move()
{
std::cout << "MOVE IS CALLED" << std::endl;
//mutal_state.lock();
//previousState = currentState;
//std::cout << "MOVING" << std::endl;
//currentState = nextState;
//mutal_state.unlock();
}
Program runs concurrently.
My suggestions:
1) if you have no debugger, how can you be so sure it is the first line of move that crashes? It is always with questioning any assumptions you have made about the code, unless you have hard evidence to back it up.
2) I would look at whatever interesting code is in state s3, as this is what the first call to move will perform. Up to that point the code in s3 has not been run. Either that or remove all code bar what is in the posted example, to rule this out.
3) The compiler may make copies of the variables in registers, you should declare all the states as volatile so it knows not to optimise in this way.
I can not help you why your code "explodes", however I can assume that the problem is not in the code you posted as it runs fine for me.
This will output for me:
I'm working
...
Bye
Code:
int main() {
Robot r;
auto async_moves = [&] () { // simulate some delayed interaction
std::this_thread::sleep_for(std::chrono::seconds(2)); //See note
for(auto i = 0; i != 3; ++i)
r.move();
};
auto handle = std::async(std::launch::async, async_moves);
r.run();
}
(Note: You have to compile with -D_GLIBCXX_USE_NANOSLEEP assuming you are using gcc, see this question.)
Note that the code above - and yours maybe, too - is still vulnurable to the problem, that the states may get invalidated if move is called twice or more before the loop triggers again.
Like one of the comments already mentioned, prefer to use lock_guards:
std::lock_guard<std::mutex> lock(mutal_state);
If you're using g++ on linux, you need to link with -lpthread in order for mutexes or threading stuff to work properly. If you don't, it won't fail to link, but will instead behave badly or crash at runtime...
I'm answering my own question! Because I find the problem, and It was not related to locking nor mutex implementation of C++0x. There is an ImageProcess class that should control state of Robot. It has a pointer to it's parent of type Robot* and using that, will move its parent. For that I've implemented a workhorse and a starter function. The start spawns a std::tread and runs workhorse on it:
void ImageProcess::start()
{
std::thread x(&ImageProcess::workhorse, *this);
x.detach();
}
I realized that this->parent in workhorse is a dangling pointer. Obviously calling parent->move() should crash. But it don't crash immediately! Surprisingly program control enters into move() function and then tries to change previousState of a non-existing Robot thing. (or lock a mutex of non-existing Robot).
I found that when invoking a thread like std::thread x(&ImageProcess::workhorse, *this); x.join() or x.detach(), the code is no longer running in caller object. To test I printed address of this and &image in both Robot::run() and ImageProcess::workhorse. There were different. I also added a public boolean foo to ImageProcess and changed its value to true in Robot, then printed it in workhorse and run, in workhorse value is always 0 but in Robot is 1.
I believe this is very strange behavior. I don't know if it's related to memory model or ownership of ImageProcess somehow is changed after std::thread x(&ImageProcess::workhorse, *this)...
I make ImageProcess a factory pattern class (everything is static!). Now it's OK.