首先是“正确的”,因为我想人们会告诉我从类中启动线程是一种不好的做法。:) 所以我想知道在析构函数中停止无限线程的最佳方法是什么。在设置标志关闭时包装线程在尝试中调用并抛出异常的函数?只是好的旧整数/枚举?好的新 std::atomic int?还有什么?现在我使用:
//in destructor I call terminate member func
void terminate()
{
currentStatus=terminating;
std::cout<<"trying to kill"<<std::endl;
while (currentStatus!=terminated)
std::this_thread::yield();
std::cout<<"MISSION ACOMPLISHED"<<std::endl;
}
线程运行的功能是:
while (currentStatus==active)
{
//...
}
currentStatus=terminated;
currentStatus 是一个枚举:
enum status{
active,
terminating,
terminated
};