是否可以为调用
std::thread::join()
设置超时时间?我希望处理线程运行时间过长或终止线程的情况。我可能会为多个线程(比如最多30个线程)执行此操作。
最好不要boost,但如果这是最好的方式,我会对boost解决方案感兴趣。
发布于 2012-03-31 03:14:13
std::thread::join()
没有超时。但是,您可以将
std::thread::join()
仅仅看作是一个方便的函数。使用
condition_variable
,您可以在线程之间创建非常丰富的通信和协作,包括计时等待。例如:
#include <chrono>
#include <thread>
#include <iostream>
int thread_count = 0;
bool time_to_quit = false;
std::mutex m;
std::condition_variable cv;
void f(int id)
std::lock_guard<std::mutex> _(m);
++thread_count;
while (true)
std::lock_guard<std::mutex> _(m);
std::cout << "thread " << id << " working\n";
std::this_thread::sleep_for(std::chrono::milliseconds(250));
std::lock_guard<std::mutex> _(m);
if (time_to_quit)
break;
std::lock_guard<std::mutex> _(m);
std::cout << "thread ended\n";
--thread_count;
cv.notify_all();
int main()
typedef std::chrono::steady_clock Clock;
std::thread(f, 1).detach();
std::thread(f, 2).detach();
std::thread(f, 3).detach();
std::thread(f, 4).detach();
std::thread(f, 5).detach();
auto t0 = Clock::now();
auto t1 = t0 + std::chrono::seconds(5);
std::unique_lock<std::mutex> lk(m);
while (!time_to_quit && Clock::now() < t1)
cv.wait_until(lk, t1);