在此处使用以下信息:How to check if a thread is still running我尝试使用lambda function
中的std::future
在专用member function
中拨打课程thread
这样就可以使用std::future
future.wait_for()
线程的完成状态
TestClass创建std::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;
function = std::bind(&TestClass::Snooze, this, std::placeholders::_1, std::placeholders::_2);
future = std::async(std::launch::async, [this] {
function(nap, &run);
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(1));//needs to have a value > 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
}
std::cout << "TestClass: Finished Snoozing." << std::endl;
}
//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: stopSnooze(): 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(1);//should see some zzzz's here
std::this_thread::sleep_for(std::chrono::seconds(5));
tc.stopSnooze();//demonstrate stopping the thread by setting run = false
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "TestClass: Next test." << std::endl;
TestClass tc1(1);//should see some zzzz's here
std::this_thread::sleep_for(std::chrono::seconds(5));
}
编辑:更正了代码以按预期运行。
答案 0 :(得分:2)
我把这个作为重复投票,但实际上你只是有一个错字:
auto function = std::bind(&TestClass::Snooze, this, nap, &run);
auto future = std::async(std::launch::async, [&function]{
function();
return true;
});
应该是:
function = std::bind(&TestClass::Snooze, this, nap, &run);
future = std::async(std::launch::async, [this] {
function();
return true;
});
您想要分配给您的会员,而不是创建临时工。原样,您的构造函数是blocking on the future destructor。