Boost logo

Boost :

Subject: [boost] [thread] countdown_latch
From: Michael Marcin (mike.marcin_at_[hidden])
Date: 2013-04-21 04:27:39


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.

However that work clutters up the code quite a bit with the
implementation details.

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_;
};


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk