gpt4 book ai didi

c++ - 什么时候应该使用 std::thread::joinable?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:22:05 27 4
gpt4 key购买 nike

关于 std::thread::joinable 的网站 cppreference 上有说明:

Checks if the thread object identifies an active thread of execution. Specifically, returns true if get_id() != std::thread::id(). So a default constructed thread is not joinable. A thread that has finished executing code, but has not yet been joined is still considered an active thread of execution and is therefore joinable.

接下来是 std::thread::join文档:

Error Conditions

resource_deadlock_would_occur if this->get_id() == std::this_thread::get_id() (deadlock detected)

这种方法的唯一目的是检测这种情况吗?我们目前厚颜无耻地只调用 thread->join 而没有可连接的包装器,这种方法有什么危险?

最佳答案

根据您引用的信息:

So a default constructed thread is not joinable.

这就是你的答案。如果您不知道您的线程是否是默认构造的,您就不知道它是否可连接。

因此,在您的程序/函数/例程即将结束时,当您想加入线程时(并且您确实需要这样做,在 std::thread 超出范围之前) ,您必须有条件地这样做。这就是您如何做到这一点。

#include <thread>

void bar(const unsigned int);

/**
* This class may be default-constructed (in which case it does nothing),
* or constructed with an `unsigned int` argument which shall be passed
* to `bar()` in a worker thread.
*/
struct Foo
{
Foo() {}

Foo(const unsigned int x)
: doThingsThread([&]() { bar(x); })
{}

~Foo()
{
// The thread *MUST* be joined before destruction, if it
// is joinable. Otherwise, it *CAN'T* be joined.
if (doThingsThread.joinable())
doThingsThread.join();
}
private:
std::thread doThingsThread;
};

关于c++ - 什么时候应该使用 std::thread::joinable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42924503/

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