Timeout for thread.join()

前端 未结 5 2209
暗喜
暗喜 2020-12-01 15:44

Is it possible to set a timeout for a call to std::thread::join()? I want to handle the case in which the thread is taking too long to run, or terminate the th

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-01 16:31

    Yes, it is possible. The solution that has been suggested by Galik looks like this:

    #include 
    #include 
    ...
    // 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. --- */
    
    }
    

    However, this essentially launches a third thread that performs the thread.join().

    (Note: The destructor of future will block until thread has joined and the auxiliary thread has terminated.)


    Maybe launching a thread just to bring another thread down is not what you want. There is another, portable solution without an auxiliary thread:

    #include 
    #include 
    ...
    // Launch the thread.
    std::future*  hThread 
      = new std::future(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;
    

    where T_return is the return type of your thread procedure. This scenario uses an std::future / std::async combination instead of an std::thread.

    Note that hThread is a pointer. When you call the delete operator on it, it will invoke the destructor of *hThread and block until the thread has terminated.

    I have tested both versions with gcc 4.9.3 on Cygwin.

提交回复
热议问题