我有一个运行两个不同操作的程序,我想在它们之间共享变量。
目前,我正在使用线程而不是 fork 进程,但我在共享变量时遇到了问题,即使我将它们声明为 volatile。
我试着用 boost 做:
boost::thread collisions_thread2(boost::bind(function_thread2);
通过将共享变量声明为 volatile,但 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
}
关于C++,如何在进程或线程之间共享数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9505131/