首页 > 解决方案 > 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

有任何想法吗?提前致谢!

标签: multithreadingc++11boostboost-thread

解决方案


如果您在线程之间共享数据,则必须同步对该数据的访问。两种可能的方式是保护所述数据的互斥锁和原子操作。简单的原因是存在缓存和读/写重新排序(由 CPU 和编译器)。虽然这是一个复杂的话题,在这里的答案中没有什么可以解释的,但是那里有几本好书,还有一堆正确的代码。


推荐阅读