multithreading - boost::thread 不更新全局变量
问题描述
我在外部软件中使用包装函数来启动一个新线程,该线程更新一个全局变量,但这似乎对主线程不可见。我不能调用 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
有任何想法吗?提前致谢!
解决方案
如果您在线程之间共享数据,则必须同步对该数据的访问。两种可能的方式是保护所述数据的互斥锁和原子操作。简单的原因是存在缓存和读/写重新排序(由 CPU 和编译器)。虽然这是一个复杂的话题,在这里的答案中没有什么可以解释的,但是那里有几本好书,还有一堆正确的代码。
推荐阅读
- bash - CURL PUT 请求到一个 RESTful API
- c# - System.IO.Directory.Exists 在目录存在时返回 false
- php - 如何在 PHP 中将 1e8 值转换为普通整数?
- javascript - 使用 express 将嵌套的 mongodb 文档推送到数组时遇到问题
- c# - Json 到 C# 没有正确反序列化货币符号
- angular - Angular 6 反应形式示例在 plunker 上失败
- angular - ngFor 如何根据键值将值包装在 div 容器中
- vue.js - 页面更改时无法在 Vuejs 中查看来自 Janus-Gateway 的流
- python - 总结两个文本文件并在python中创建一个新文件
- python - 如何将字符串中的连续字母和连续数字分别合并到列表中?