This question already has an answer here:
Using information here:How to check if a thread is still running I'm trying to use a lambda function
in a std::future
to call a class member function
in a dedicated thread
so that the std::future
may be monitored for the completion status of the thread using future.wait_for()
This demonstration code will not run. The TestClass creates a std::future
& starts a thread in its constructor. The intention is to allow other member functions to monitor progress and terminate that thread when necessary.
#include <future>
#include <future>
#include <thread>
#include <chrono>
#include <iostream>
#include <atomic>
#include <functional>
class TestClass
{
public:
TestClass(const int &np) : nap(np), run(true)
{
// Run member function in a thread, crucially be
// able to monitor the thread status using the future;
auto function = std::bind(&TestClass::Snooze, this, nap, &run);
auto future = std::async(std::launch::async, [&function]{
function();
return true;
});
}
~TestClass()
{
//If future thread is still executing then terminate it by setting run = false
//Use wait_for() with zero milliseconds to check thread status.
auto status = future.wait_for(std::chrono::milliseconds(0));
if (status != std::future_status::ready)//execution not complete
{
run = false;//terminate Snooze
future.wait();//wait for execution to complete
}
std::cout << "TestClass: destructor completed" << std::endl;
}
void Snooze(const int napLen, std::atomic<bool> *ptrRun)
{
while (*ptrRun)//check ok to to loop on.
{
std::cout << "zzzz...." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(napLen));//take a nap
}
}
//Getter
bool isThreadFinished() const
{
auto status = future.wait_for(std::chrono::milliseconds(0));
if (status == std::future_status::ready)//execution complete
{
return true;
}
else
{
return false;
}
}
//Setter
void stopSnooze()
{
run = false;
std::cout << "TestClass: run = " << run << std::endl;
}
private:
int nap;
std::function<void(int, std::atomic<bool>*)> function;
std::future<bool> future;
std::atomic<bool> run;
};
int main() {
TestClass tc(3);//should see some zzzz's here
std::this_thread::sleep_for(std::chrono::seconds(9));
tc.stopSnooze();//demonstrate stopping the thread by setting run = false
TestClass tc1(3);//should see some zzzz's here
std::this_thread::sleep_for(std::chrono::seconds(6));
tc.~TestClass();//demonstrate stopping the thread when the destructor is called
}
Program seizes at this entry in the call stack:
futureDemo.exe!std::_Pmf_wrap *),void,TestClass,int,std::atomic *>::operator()(TestClass * _Pfnobj, int , std::atomic * ) Line 1230 C++
Is anyone please able to demonstrate what's wrong or correct this so it will run as intended?
Aucun commentaire:
Enregistrer un commentaire