假设我有一个工作线程,它在构造tWorker
时初始化并告诉它执行,直到为真。An , , 锁定一些数据 ( ) 以便在他处理它时拥有它。Boss
work()
bRetired
std::mutex
mtx
vFiles
tWorker
我如何让tWorker
“自杀”bRetired
变成一次true
?mutex
当线程停止执行时将如何销毁?
我读过std::thread
对象不能以任何方式被打断。让线程什么都不做(或调用std::this_thread::yield()
)是否提供与杀死线程相同的效果?
class Boss {
private:
std::thread tWorker;
std::mutex mtx;
bool bRetired;
std::vector< std::string > vFiles;
void work() {
while ( bRetired == false ) {
// Do your job!
mtx.lock();
// ... Do something about vFiles ...
mtx.unlock();
}
// tWorker has retired, commit suicide
// ** How? **
// Does this suffice if I want to "kill" the thread?
std::this_thread::yield();
}
public:
Boss() {
bRetired = false;
tWorker = std::thread( &Boss::work, this );
// Have worker do its job independently
// **Bonus Question** : Should this be tWorker.join() or tWorker.detach()?
tWorker.detach();
}
retire() {
bRetired = true;
}
}
笔记
- 工作线程一旦退役就无法再次启动。
- 工作线程在后台工作,不会中断主线程的执行。