gpt4 book ai didi

C++11:如何在执行函数退出后立即加入 std::thread?

转载 作者:行者123 更新时间:2023-12-02 05:55:26 31 4
gpt4 key购买 nike

我有以下类,其中 std::thread 作为其成员字段之一:

class MyClass {
private:
std::thread auxThread;
void run();
public:
~MyClass();
void start();
}

MyClass:~MyClass() {
if (auxThread.joinable())
auxThread.join();
}

void MyClass::run() {
//do stuff
}

void MyClass::start() {
auxThread = std::thread (&MyClass::run, this); //Move assignment
}

我可以按需启动 auxThread,这要归功于使用空构造函数初始化它,然后将其移动分配给与实际执行线程关联的 std::thread 对象(通过 start() 函数),但是最小化系统资源使用我想在 run() 退出后立即 join() auxThread 与主线程,即当 auxThread 的工作完成时而不是在 MyClass 析构函数中。看起来像 condition_variable可以用来唤醒休眠的主线程并完成此任务,但我不想阻塞主线程,除非(希望)使用 join() 短暂地阻塞。

两个问题:

  1. 有一个线程,其执行函数已退出,如果它从未与主线程连接,则会耗尽资源,或者当执行函数退出时,线程和所有关联的资源都会被释放(这样 join() 将大概是不必要的并立即返回)?

  2. 是否可以从主线程调用 auxThread 上的 join() 来响应 run() 退出而不阻塞主线程?

最佳答案

Is having a thread whose execution function has exited a drain on resources if it is never joined with the main thread

也许吧。这取决于您的实现,但通常不是。

is the thread and all associated resources released when the execution function exits

可能,如果没有,那么操作系统会尽快。这也是实现定义的。

Is it possible to call join() on auxThread from the main thread in response to run() exiting without blocking the main thread?

是的,但这没有任何意义。 join 唯一做的就是阻塞,直到正在执行的函数完成为止。 run 执行完成后再次调用 join 是不必要的,基本上是无操作。

此外,线程的“资源”很少。我不认为会为像您这样的单个线程分配大量内存。如今 RAM 相当便宜,所以您不必担心这一点,因为您没有并行执行 5M 线程,这在传统计算机上无论如何都是没有意义的。

关于C++11:如何在执行函数退出后立即加入 std::thread?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50536200/

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