Timeout for thread.join()

Timeout for thread.join()

本文关键字:join thread for Timeout      更新时间:2023-10-16

是否可以为调用std::thread::join()设置超时?我想处理线程运行时间过长或终止线程的情况。我可能会为多个线程(例如,最多30个线程)执行此操作。

最好不要升压,但如果这是最好的方法,我会对升压解决方案感兴趣。

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 << " workingn";
        }
        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 endedn";
    --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 endingn";
    while (thread_count > 0)
        cv.wait(lk);
    std::cout << "main endedn";
}

在这个例子中,main启动几个线程来完成工作,所有这些线程偶尔都会检查是否是时候在互斥对象下退出了(这也可能是原子)。主线程还监视是否该退出(如果线程完成了所有工作)。如果main没有耐心,他只会宣布是时候退出了,然后等待所有线程在退出之前执行任何必要的清理。

是的,这是可能的。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测试了这两个版本。

您可以使用std::async()为您提供std::future<>,而不是显式使用线程,并且您可以在std::future:上进行定时等待

http://en.cppreference.com/w/cpp/thread/future/wait_for

对于Boost,timed_join()现在已被弃用。改为使用try_join_for():

myThread.try_join_for(boost::chrono::milliseconds(8000))

对于Boost,请参阅timed_join()以了解带超时的join()版本。

函数执行带超时的联接。如果线程尚未终止,那么调用将阻塞,直到达到在abstime中指定的最长时间。如果在线程终止之前超时,那么调用将返回一个错误。

int pthread_timedjoin_np(pthread_t thread, void **retval, const struct timespec *abstime);

编译并使用-phread链接。