【发布时间】:2017-05-11 08:24:03
【问题描述】:
我有一个“监视线程”,它检查其他线程是否正在运行并计算一些数据。如果这些线程结束,我也想完成我的观察线程。我该怎么做?
#include <iostream>
#include <thread>
using namespace std;
void f1() {
cout << "thread t1" << endl;
for (int i=0; i<1000; ++i) {
cout << "t1: " << i << endl;
}
}
void f2() {
cout << "thread t2" << endl;
while (T1_IS_RUNNING) {
cout << "t1 still running" << endl;
}
}
int main() {
thread t1(f1);
thread t2(f2);
t1.join();
t2.join();
return 0;
}
在上面的例子中我需要实现T1_IS_RUNNING。任何想法如何做到这一点?我的猜测是获取正在运行的线程数,但我在 STL 中没有找到任何相关方法。
已经有一个How to check if a std::thread is still running?,但我认为他们对我的情况使用了过于复杂的解决方案。一个简单的线程计数器 (std::atomic) 还不够好吗?
【问题讨论】:
标签: c++ multithreading c++11