gpt4 book ai didi

c++ - 线程如何在完成时发出信号?

转载 作者:行者123 更新时间:2023-11-30 00:41:45 25 4
gpt4 key购买 nike

#include <iostream>
#include <boost/thread.hpp>
using std::endl; using std::cout;
using namespace boost;


mutex running_mutex;

struct dostuff
{
volatile bool running;
dostuff() : running(true) {}
void operator()(int x)
{
cout << "dostuff beginning " << x << endl;
this_thread::sleep(posix_time::seconds(2));
cout << "dostuff is done doing stuff" << endl;
mutex::scoped_lock running_lock(running_mutex);
running = false;
}
};

bool is_running(dostuff& doer)
{
mutex::scoped_lock running_lock(running_mutex);
return doer.running;
}

int main()
{
cout << "Begin.." << endl;
dostuff doer;
thread t(doer, 4);

if (is_running(doer)) cout << "Cool, it's running.\n";

this_thread::sleep(posix_time::seconds(3));

if (!is_running(doer)) cout << "Cool, it's done now.\n";
else cout << "still running? why\n"; // This happens! :(

return 0;
}

为什么上面程序的输出是:

Begin..
Cool, it's running.
dostuff beginning 4
dostuff is done doing stuff
still running? why

dostuff 如何在完成时正确标记?我不想坐等它,我只想在它完成时收到通知。

最佳答案

这个例子中的问题是 dostuff 有两个实例,所以 operator() 中设置为 false 的版本与 main 中的不同。

来自thread management documentation :

A new thread is launched by passing an object of a callable type that can be invoked with no parameters to the constructor. The object is then copied into internal storage, and invoked on the newly-created thread of execution. If the object must not (or cannot) be copied, then boost::ref can be used to pass in a reference to the function object. In this case, the user of Boost.Thread must ensure that the referred-to object outlives the newly-created thread of execution.

如果你不想复制对象,使用boost::ref:

thread t(boost::ref(doer), 4);

关于c++ - 线程如何在完成时发出信号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2925881/

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