c++ - 可以从非父线程调用 std::thread::join() 吗?

标签 c++ multithreading c++11

A::threadmain 线程创建。我可以将 A::thread 加入到线程 goo 中吗?

struct A {
   std::thread thread;   
   void foo() {
       thread=std::thread{[]() { sleep(10); }};
   }
};

void goo(A& a) {
   a.thread.join();
}

int main() {
    A a;
    a.foo();
    std::thread other_thread{goo, a};
    other_thread.join();
};

最佳答案

是的,你可以。 std::thread::join 的行为是(强调我的):

Blocks the current thread until the thread identified by *this finishes its execution.

它非常明确地表示“当前线程”,而不是“父线程”。任何线程都可以与任何其他线程连接,只要它具有该其他线程的有效句柄即可。

尽管在使用对线程对象的引用时必须注意数据竞争。两个不同的线程试图加入同一个第三个线程会……很糟糕。

关于c++ - 可以从非父线程调用 std::thread::join() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50481501/

相关文章:

wcf - 关闭具有线程的 Windows 服务

java - 同一数组的两个不同输出

c++ - std type_traits 与 Qt type_traits 冲突

c++ - 你如何在 C++ 中的 priority_queue 中排序对象?

c++ - 从类返回不正确的值

c++ - 使用复制构造函数创建对象(三类简单规则)会产生运行时错误

新线程内的 android.os.networkonmainthreadexception

c++ - 如何从 C stdio.h getline() 中替换/忽略无效的 Unicode/UTF8 字符?

c++ - 可变参数子集

c++ - 隐藏C++模板类成员函数的定义