是否可以为std::thread::join()
的通话设置超时?我想处理线程运行时间太长或终止线程的情况。我可能会为多个线程(例如,最多30个)执行此操作。
最好没有提升,但如果这是最佳方式,我会对提升解决方案感兴趣。
答案 0 :(得分:17)
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);
time_to_quit = true;
std::cout << "main ending\n";
while (thread_count > 0)
cv.wait(lk);
std::cout << "main ended\n";
}
在这个示例中,main
启动了几个线程来完成工作,所有这些线程偶尔会检查是否需要在互斥锁下退出(这也可能是一个原子)。主线程还监视是否是时候退出(如果线程完成所有工作)。如果main没有耐心,他只是声明是时候退出,然后在退出之前等待所有线程执行任何必要的清理。
答案 1 :(得分:6)
是的,有可能。 Galik建议的解决方案如下:
#include <thread>
#include <future>
...
// Launch the thread.
std::thread thread(ThreadFnc, ...);
...
// Terminate the thread.
auto future = std::async(std::launch::async, &std::thread::join, &thread);
if (future.wait_for(std::chrono::seconds(5))
== std::future_status::timeout) {
/* --- Do something, if thread has not terminated within 5 s. --- */
}
但是,这实际上启动了执行thread.join()
。
(注意:future
的析构函数将阻塞,直到thread
加入并且辅助线程已终止。)
也许启动一个线程只是为了让另一个线程失效不是你想要的。还有另一种没有辅助线程的便携式解决方案:
#include <thread>
#include <future>
...
// Launch the thread.
std::future<T_return>* hThread
= new std::future<T_return>(std::async(std::launch::async, ThreadFnc, ...));
...
// Terminate the thread.
if (hThread->wait_for(std::chrono::seconds(5))
== std::future_status::timeout) {
/* --- Do something, if thread has not terminated within 5 s. --- */
} else
delete hThread;
其中T_return
是线程过程的返回类型。此方案使用std::future
/ std::async
组合而不是std::thread
。
请注意hThread
是一个指针。当你调用delete
运算符时,它将调用*hThread
的析构函数并阻塞直到线程终止。
我在Cygwin上使用gcc 4.9.3测试了两个版本。
答案 2 :(得分:4)
timed_join()现已弃用。请改用try_join_for():
myThread.try_join_for(boost::chrono::milliseconds(8000))
答案 3 :(得分:4)
您可以使用std::async()
为std::future<>
提供std::future
而不是明确使用线程,您可以在{{1}}上进行定时等待:
答案 4 :(得分:3)
对于Boost,请参阅timed_join()以获取具有超时的join()版本。
答案 5 :(得分:0)
pthread_timedjoin_np() 函数执行超时连接。如果线程尚未终止,则调用将阻塞,直到以 abstime 指定的最长时间为止。如果超时在线程终止之前到期,则调用将返回错误。
int pthread_timedjoin_np(pthread_t thread, void **retval, const struct timespec *abstime);
使用 -pthread 编译和链接。