Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can std::thread::join() be called from a non parent thread?

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();
};
like image 974
themagicalyang Avatar asked Jan 03 '23 08:01

themagicalyang


1 Answers

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.

like image 157
StoryTeller - Unslander Monica Avatar answered Jan 05 '23 17:01

StoryTeller - Unslander Monica