A::thread
was created by main
thread. Can I join A::thread
into the 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();
};
Yes, you may. The behavior of std::thread::join
is (emphasis mine):
Blocks the current thread until the thread identified by
*this
finishes its execution.
It says quite explicitly "current thread", not "parent thread". Any thread can join with any other thread, so long as it has a valid handle to that other thread.
Though you have to mindful of data races when using references to thread objects. Two different threads attempting to join the same third one would be... bad.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With