【发布时间】:2020-05-23 23:49:40
【问题描述】:
我在外部软件中使用包装函数来启动一个新线程,该线程会更新一个全局变量,但这对主线程来说似乎是不可见的。我不能调用 join(),而不是阻塞主线程并使软件崩溃。 boost::async、boost::thread 和 boost::packaged_task 的行为方式都相同。
uint32 *Dval;
bool hosttask1()
{
while(*Dval<10)
{
++*Dval;
PlugIn::gResultOut << " within thread global value: " << *Dval << std::endl;
Sleep(500);
}
return false;
}
void SU_HostThread1(uint32 *value)
{
Dval = value;
*Dval = 2;
PlugIn::gResultOut << " before thread: " << *value << " before thread global: " << *Dval << std::endl;
auto myFuture = boost::async(boost::launch::async,&hosttask1);
//boost::thread thread21 = boost::thread(&hosttask1);
//boost::packaged_task<bool> pt(&hosttask1);
//boost::thread thread21 = boost::thread(boost::move(pt));
}
当我调用函数时:
number a=0
su_hostthread1(a)
sleep(2) //seconds
result(" function returned "+a+" \n")
OUTPUT:
before thread value: 2 before thread global value: 2
within thread global value: 3
within thread global value: 4
within thread global value: 5
within thread global value: 6
function returned 2
within thread global value: 7
within thread global value: 8
within thread global value: 9
within thread global value: 10
有什么想法吗? 提前致谢!
【问题讨论】:
-
这是
Dval上的教科书数据竞赛,行为未定义。 -
您的示例代码包含错误,因此无法讨论。请更改它,使其提供minimal reproducible example。作为这里的新用户,也请带上tour并阅读How to Ask。
标签: multithreading c++11 boost boost-thread