开发者

Returning values from thread specific code using boost threads

开发者 https://www.devze.com 2023-02-17 04:08 出处:网络
I\'m using C++ boost library threads like this MyThread alarm(); boost::thread thrd(alarm); if (thrd.timed_join(boost::posix_time::seconds(timeout)))

I'm using C++ boost library threads like this

MyThread alarm();
boost::thread thrd(alarm);
if (thrd.timed_join(boost::posix_time::seconds(timeout)))
{
    cout << alarm.modified_var << endl;
}
else
{
    cout &开发者_Go百科lt;< alarm.modified_var << endl;
}

modified_var is changed inside MyThread class but when I print it later after synchronization point i get unitialized value of modified_var. What am I doing wrong?


That is because the alarm-object is copied when passed to the thread constructor. The solution is to wrap it in a boost::ref:

boost::thread thrd(boost::ref(alarm));
0

精彩评论

暂无评论...
验证码 换一张
取 消