- 1 year ago
How should I wait for thread to finish with a timeout using C++11?
In C++11, you can use the std::condition_variable
and std::mutex
classes to implement a timeout for waiting on a thread to finish. Here is an example code snippet:
c++#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
void MyThreadFunction()
{
// Do some work here
}
int main()
{
std::thread myThread(MyThreadFunction);
// Wait for the thread to finish with a timeout of 5 seconds
std::mutex mutex;
std::condition_variable conditionVariable;
bool isFinished = false;
std::unique_lock<std::mutex> lock(mutex);
auto timeout = std::chrono::system_clock::now() + std::chrono::seconds(5);
while (!isFinished && conditionVariable.wait_until(lock, timeout) != std::cv_status::timeout)
{
// Check if the thread has finished
if (myThread.joinable() && myThread.joinable())
{
myThread.join();
isFinished = true;
}
}
if (!isFinished)
{
myThread.detach();
// Handle the timeout here
}
return 0;
}
In this code snippet, we create a thread using the std::thread
class and wait for it to finish with a timeout of 5 seconds. We use a std::mutex
and std::condition_variable
to implement the timeout. The std::unique_lock
is used to lock the mutex, and the wait_until
function of the condition_variable
is used to wait until either the thread has finished or the timeout has expired. If the thread has finished before the timeout, we call join()
on the thread to wait for it to finish. If the timeout expires before the thread has finished, we detach the thread using detach()
and handle the timeout accordingly.