Boost logo

Boost :

Subject: Re: [boost] [thread] countdown_latch
From: Rob Stewart (robertstewart_at_[hidden])
Date: 2013-04-21 06:54:23


On Apr 21, 2013, at 4:27 AM, Michael Marcin <mike.marcin_at_[hidden]> wrote:

> 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_wait.html

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)


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