dimanche 28 février 2016

Two STL threads wait on a third thread—do with joinable?

I want two threads (let's call them t1 and t2) to wait for one other thread, t0. Let's simplify matters and say t1 and t2 are both worker threads. I don't think the following code will work correctly.

/* ... code both t1 and t2 run ... */
if (t0.joinable()) { 
  /* race condition here */
  t0.join();
}

It's possible for both t1 and t2 to get true for joinable, and then whichever joins first wins and the other one probably segfaults—right? So what is the correct way to have two threads wait on a single third thread?

Is there a way to do this just with joins of the STL, or does t0 need to set some sort of (atomic) done flag or use a condition variable?

Aucun commentaire:

Enregistrer un commentaire