[英]Improve multi thread communication?
Here is the code on thread #1: 这是线程#1上的代码:
move = false;
//start thread #2
while(!move) Sleep(5);
//do stuff
Thread #2 code: 线程2代码:
//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? 使用C ++ 11? Use std::condition_variable.
使用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 线程#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 线程#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. Future是用于表示异步操作结果的更高级别的构造。
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. Future
对象并保留对其的引用,并将引用传递给执行异步操作的线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.