On Apr 21, 2013, at 4:27 AM, Michael Marcin
I recently ran across the need to spawn a thread and wait for it to finish its setup before continuing.
The accepted answer seems to be using a mutex and condition variable to achieve this.
That works, and is the appropriate mechanism using the available tools in Boost.Thread.
However that work clutters up the code quite a bit with the implementation details.
Agreed
I came across Java's CountDownLatch which does basically the same work but bundles it up into a tidy package.
It seems to be a fairly trivial but useful abstraction.
implementation: http://codepad.org/E8kd2Eb8
usage:
class widget { public: widget() : latch( 1 ) , thread_( [&]{ thread_func(); } ) { latch.wait(); }
private: void setup(); void run();
void thread_func() { setup(); latch.count_down(); run(); }
countdown_latch latch; std::thread thread_; };
That sounds like a barrier: http://pubs.opengroup.org/onlinepubs/009695299/functions/pthread_barrier_wai... I'd prefer to create a barrier class and, in your example, it would release waiting threads when two are blocked behind it. IOW, you'd create a barrier for two threads and both thread_proc() and the constructor would wait() on the barrier. Once both threads have called wait(), they are both released. (I plan to present that at C++ Now, this year.) Your idea is sound, but I'd prefer following the pthreads naming to that of Java. ___ Rob (Sent from my portable computation engine)