Search code examples
c++multithreadingc++11terminate

How can you cleanly terminate a process in C++11?


I wonder if there is a good way to terminate my process written in C++11 after a while?

In my process I have a main class with a pure virtual function run() running the main program that could be blocked in communication processes. I want my run() function to be forced to finish after a while (even if blocked) and the destructor of my main class (and all the destructors of the members) to be called.

Now I have a timer that call std::terminate via a callback.

namespace Timer
{
    void start(Duration time, function<void()> task)
    {
        thread([time, task]() {
            this_thread::sleep_for(time);
            task();
        }).detach();
    }
}

Solution

  • The best solution is to wrap run() in a thread.

    std::thread([&]()
    {
       run();
       finish.notify_all();
    }).detach();
    
    std::unique_lock<std::mutex> lock(waitFinish);
    finish.wait_for(lock, time);