Here is the code on thread #1:
move = false;
//start thread #2
while(!move) Sleep(5);
//do stuff
Thread #2 code:
//do stuff
move = true;
Is there a better way to wait for the change of move, for example, doing what is called block till data are read in networking?
Using C++11? Use std::condition_variable.
What you have is a way.
There other things you can use. A few come to my mind:
Using conditions
A condition is somewhere where you can wait() for other part (thread) of the code to signal() you can continue
Conditions are associated to a mutex
In your code:
Thread #1
// start thread #2
mutex.acquire();
// You could check for an actual condition here if it
// is more complex than a true false.
condition.wait();
// If we're checking for a complex condition here
// we should re-evaluate in case it is not satisfied.
mutex.release();
Thread #2
// do stuff
mutex.acquire();
condition.signal();
mutex.release();
Using a Future
A Future is a higher level construct for representing the result of an asynchronous operation.
It works more or less like this:
Future
object and keeps a reference to it and passes a reference to the thread performing the asynchronous operation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.