[英]Improve multi thread communication?
这是线程#1上的代码:
move = false;
//start thread #2
while(!move) Sleep(5);
//do stuff
线程2代码:
//do stuff
move = true;
是否有更好的方法来等待移动的变化,例如,在网络中读取数据之前执行所谓的阻止操作?
使用C ++ 11? 使用std :: condition_variable。
你拥有的是一种方法。
还有其他可以使用的东西。 我想到了一些:
使用条件
条件是您可以在其中等待代码的其他部分(线程) 发出信号(可以继续)的条件
条件与互斥锁相关
在您的代码中:
线程#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();
线程#2
// do stuff
mutex.acquire();
condition.signal();
mutex.release();
使用未来
Future是用于表示异步操作结果的更高级别的构造。
它或多或少是这样的:
Future
对象并保留对其的引用,并将引用传递给执行异步操作的线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.