A::thread
由 main
线程创建。我可以将 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/