gpt4 book ai didi

c++ - 告诉 std::thread 在满足条件时终止/停止自身

转载 作者:可可西里 更新时间:2023-11-01 15:57:13 27 4
gpt4 key购买 nike

假设我有一个工作线程tWorker,它在构造Boss 时被初始化并告诉它执行work(),直到bRetired 为真。 std::mutexmtx,锁定一些数据(vFiles),以便 tWorker 在他工作时拥有它在上面。

一旦 bRetired 变为 true,我如何让 tWorker “自杀”?当线程停止执行时,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;
}
}

注意事项

  • 工作线程一旦退出就不能再启动。
  • 工作线程在后台工作,不会中断主线程的执行。

最佳答案

How do I make tWorker "commit suicide" once bRetired becomes true?

您让控制流退出线程函数。那std::this_thread::yield()不必要的调用。

How would the mutex be destroyed when the thread stops execution?

那个互斥锁是Boss的成员类(class)。它在 Boss 的析构函数中被销毁当对象被销毁时。

I've read that std::thread objects cannot be interrupted in any way.

C++ API 不提供终止任意线程的方法。必须有一种方法来告诉线程终止,然后等待它终止,正如您打算做的那样。

Does letting the thread do nothing (or calling std::this_thread::yield()) provide the same effect as killing the thread?

没有。

bRetired 上存在竞争条件虽然可变。它要么需要是 std::atomic<bool>或者只有当该互斥锁被锁定时才应该读取和修改它。

关于c++ - 告诉 std::thread 在满足条件时终止/停止自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18868114/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com