【发布时间】:2010-05-28 00:09:05
【问题描述】:
#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;
}
为什么是上面程序的输出:
开始..
很酷,它正在运行。
dostuff 开头 4
dostuff 做完事了
仍在运行?为什么
dostuff 完成后如何正确标记?我确实不想坐在那里等它,我只想在它完成时收到通知。
【问题讨论】:
-
我知道你不想只是坐在那里。但是你应该在一个循环中检查
is_running(可能也在循环中做其他工作)。完成后,您应该加入。否则就是资源泄漏。 -
请注意,“volatile”并不真正意味着“可用于在线程之间传递消息”,尽管在大多数编译器中都是这样。建议使用适当的线程通信机制,如锁。此外,如果这实际上是应用程序的一部分,而不仅仅是示例代码,则 boost 的条件会为您提供一个超时等待,它可以代替您的睡眠。
标签: c++ multithreading boost boost-thread