Question #246642

Using your Operating Systems knowledge of threads. Model what happens with an example of code of How to interupt a thread in C++

Expert's answer

When you want to interrupt a thread, you simply write synchronously to the variable, and then you join the thread. If it cooperates appropriately, it should notice that that the variable has been written and shut down, resulting in the join function no longer blocking.

#include <thread>
#include <iostream>
#include <future>
#include <assert.h>
#include <chrono>
void threadF(std::f<void> fObj)
{
    std::cout << "Start" << std::endl;
    while (fObj.wait_for(std::chrono::milliseconds(1)) == std::f_status::timeout)
    {
        std::cout << "Working" << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
    std::cout << "End" << std::endl;
}
int main()
{
    std::promise<void> exitSignal;
    std::f<void> fObj = exitSignal.get_f();
    std::thread th(&threadF, std::move(fObj));
    std::this_thread::sleep_for(std::chrono::seconds(15));
    std::cout << "Stopping thread" << std::endl;
    exitSignal.set_value();
    th.join();
    std::cout << "Exiting" << std::endl;
    return 0;
}
LATEST TUTORIALS
APPROVED BY CLIENTS