Answer to Question #246642 in C++ for Dunga

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++
1
Expert's answer
2021-10-04T23:11:11-0400

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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS