在这里使用信息:How to check if a thread is still running我正在尝试使用std::future中的lambda function来调用专用thread中的member function类,以便可以使用future.wait_for()监视std::future的线程完成状态
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));
}编辑:已更正代码以按预期运行。
发布于 2015-01-27 04:06:28
我投票认为这是一个复制品,但实际上你只是有一个打字错误:
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。
https://stackoverflow.com/questions/28157743
复制相似问题