gpt4 book ai didi

C++,如何在进程或线程之间共享数据

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:31:20 27 4
gpt4 key购买 nike

我有一个运行两个不同操作的程序,我想在它们之间共享变量。

目前,我正在使用线程而不是 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com