Mar*_*net 5 c++ multithreading fork
我有一个程序,它运行两个不同的操作,我想在它们之间共享变量.
目前,我正在使用线程而不是fork进程,但即使我将它们声明为volatile也存在共享变量的问题.
我尝试使用boost做:
boost::thread collisions_thread2(boost::bind(function_thread2);
Run Code Online (Sandbox Code Playgroud)
通过将共享变量声明为volatile,但似乎function_thread2()函数无法看到共享变量的变化.
我想做的是:
thread1:
while(true){
//..do somet stuff
check variable1
}
thread2:
while(true){
do some other stuff
check and write on variable1
}
Run Code Online (Sandbox Code Playgroud)
你能建议我在线程之间轻松共享变量的教程或方法吗?可能是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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11843 次 |
| 最近记录: |