How to Stop or Terminate a Thread
#include <thread>
#include <iostream>
#include <assert.h>
#include <chrono>
#include <future>
class Stoppable
{
std::promise<void> exitSignal;
std::future<void> futureObj;
public:
Stoppable() :
futureObj(exitSignal.get_future())
{
}
Stoppable(Stoppable&& obj) : exitSignal(std::move(obj.exitSignal)),
futureObj(std::move(obj.futureObj))
{
std::cout << "Move Constructor is called" << std::endl;
}
Stoppable& operator=(Stoppable&& obj)
{
std::cout << "Move Assignment is called" << std::endl;
exitSignal = std::move(obj.exitSignal);
futureObj = std::move(obj.futureObj);
return *this;
}
virtual void run() = 0;
void operator()()
{
run();
}
bool stopRequested()
{
if (futureObj.wait_for(std::chrono::milliseconds(0)) ==
std::future_status::timeout) {
return false;
}
return true;
}
void stop()
{
exitSignal.set_value();
}
};
class MyTask: public Stoppable
{
public:
void run()
{
std::cout << "Task Start" << std::endl;
while (stopRequested() == false) {
std::cout << "Doing Some Work" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
std::cout << "Task End" << std::endl;
}
};
int main()
{
MyTask task;
std::thread th([&]() {
task.run();
});
std::this_thread::sleep_for(std::chrono::seconds(10));
std::cout << "Asking Task to Stop" << std::endl;
task.stop();
std::this_thread::sleep_for(std::chrono::seconds(3));
th.join();
std::cout << "Thread Joined" << std::endl;
std::cout << "Exiting Main Function" << std::endl;
return 0;
}