简体   繁体   中英

Improve multi thread communication?

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:

  1. The caller creates a Future object and keeps a reference to it and passes a reference to the thread performing the asynchronous operation.
  2. The caller continues its processing while the other thread performs its task.
  3. If the caller needs the result, it will try to get it from the Future object. If the result it is not yet available, the caller will be blocked (eg using a condition/signal) until the asynchronous operation finishes and sets the value (that sends the signal).
  4. If the asynchronous operation finishes before it is needed, the caller will get the result without wait.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM