我有一个运行两个不同操作的程序,我想在它们之间共享变量。
目前,我正在使用线程而不是 fork 进程,但即使我将它们声明为易失性,我在共享变量时也遇到问题。
我尝试使用 boost 做:
boost::thread collisions_thread2(boost::bind(function_thread2);
通过将共享变量声明为易失性,但似乎 function_thread2() 函数无法看到共享变量的更改。
我想做的是这样的:
thread1:
while(true){
//..do somet stuff
check variable1
}
thread2:
while(true){
do some other stuff
check and write on variable1
}
您能给我推荐一个教程或一种在线程之间轻松共享变量的方法吗?
在这种情况下,boost 库可能有用吗?
你认为使用 fork() 更好吗?
我知道我必须使用互斥体以避免紧急情况,但我从未使用过它。
如果你可以使用boost
, 您可以使用boost::mutex
.
// mtx should be shared for all of threads.
boost::mutex mtx;
// code below for each thread
{
boost::mutex::scoped_lock lk(mtx);
// do something
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)