我有一个类,其运行方式如下:
class MyClass
{
public:
void Start();
void Stop();
void Run();
private:
boost::thread mThread;
bool mThreadShouldRun;
}
void MyClass::Start()
{
mThreadShouldRun = true;
mThread = boost::thread(&MyClass::Run, this);
}
void MyClass::Stop()
{
mThreadShouldRun = false;
mThread.interrupt();
}
void MyClass::Run()
{
while(mThreadShouldRun)
{
//DO Something
try {
boost::this_thread::sleep_for(boost::chrono::seconds(15));
} catch(boost::thread_interrupted interrupt) {
break;
}
}
}
此代码正在执行我期望的操作:启动后台线程并按需停止。
但是根据this question join()
或detach()
的回答应该始终被调用。 join()
不是我需要的,所以我选择detach()
:
void MyClass::Start()
{
mThreadShouldRun = true;
mThread = boost::thread(&MyClass::Run, this);
mThread.detach();
}
线程仍然按预期运行但mThread
变为Not-a-Thread并且我不能再在Stop()
方法中断它,因为mThread在调用{{1}后没有长时间引用该线程}}
我真的应该调用detach()吗?如果是,如何中断()分离的线程?
答案 0 :(得分:1)
只需中断线程然后等待它返回:
#include <mutex>
class MyClass
{
public:
void Start();
void Stop();
void Run();
private:
boost::thread mThread;
bool mThreadShouldRun;
}
void MyClass::Start()
{
mThreadShouldRun = true;
mThread = boost::thread(&MyClass::Run, this);
}
void MyClass::Stop()
{
mThreadShouldRun = false;// dont really needed anymore but may be ok
mThread.interrupt();
mThread.join();
}
void MyClass::Run()
{
while(mThreadShouldRun)
{
//DO Something
try {
boost::this_thread::sleep_for(boost::chrono::seconds(15));
} catch(boost::thread_interrupted interrupt) {
break;
}
}
}