In my project every class object has its own thread with infinite cycle (while(1)) inside, in which particular object functions are performed. And I’m trying to change this so that every object would perform its functions asynchronously with timers.
Basically this is how it works with thread with infinite loop:
class obj
{
public:
obj();
~obj();
//custom functions and variables
int x;
int obj_action;
move();
wait();
}
obj()
{
obj_action=1;
//when constructing object, make its thread with infinite while cycle
boost::thread make_thread(boost::bind(&obj::obj_engine,this));
}
void obj::obj_engine()
{
while(true)
{
if (obj_action==1){move();}
else if (obj_action==2){wait();}
Sleep(1);
}
}
void obj::move()
{
x++;
obj_action==2;
}
void obj::wait()
{
Sleep(5000);
obj_action==1;
}
This example shows, the obj class, which has constructor , destructor, couple of variables and couple of functions.
When constructing an object (obj()), thread is made. Thread contains a function “obj_engine” , which has infinite loop (while(true)). In the loop there is two functions:
1. wait() – makes a thread sleep for 5 seconds.
2. walk() – simply x+1
those 2 functions switches each other after its end by defining obj_action.
Now I want to change this to, when the constructing and object , asynchronously move() function would be performed, and after move() function, asynchronously wait() function would be performed, and vice verse. So I wouldn’t need to use any threads.
I hoping for result like this:
//constructing
obj()
{
asynchronous(walk());
}
walk()
{
x++
asynchronous(wait());
}
wait()
{
Sleep(5000);
asynchronous(walk());
}
I heard you can do this, with boost::asio timers , but I really don’t know how.
I would be very grateful if someone would show me how.
Here you go:
Basically everything you need is covered by the asio tutorial: this tutorial shows you how to use an asynchronous timer, and this tutorial shows you how to reset your timer.
Update:
Please use the above source code instead of my initial one – due to the repetitive calls of
io_service_.run(), eachmovecall would be called in another thread and after some time your application would crash because of it. The above code fixes this problem, and gets rid of thewaitfunction by doing so.