Boost logo

Boost :

Subject: Re: [boost] [thread] countdown_latch
From: Vicente J. Botet Escriba (vicente.botet_at_[hidden])
Date: 2013-04-22 00:30:44


Le 22/04/13 00:55, Michael Marcin a écrit :
> On 4/21/2013 4:53 PM, Vicente J. Botet Escriba wrote:
>> You are surely right. My first approach would be option 3, but it has a
>> lot of troubles as you note.
>> I suspect that the completion_latch needs a latch internally to ensure
>> that all the waiters have been finished.
>>
>> The best would be to prototype these ideas and see what can be done.
>>
>
> Back to the original example with widget for a second whether it is a
> latch or a barrier it is only used on construction but then kept
> around as member for the entire lifetime of the object.
>
> This seems unnecessary but also seems to be the pattern I've seen
> everywhere.
>
> Would it be better to do something like:
>
> class widget
> {
> public:
> widget()
> {
> countdown_latch latch(1);
> thread_ = std::thread( [&]{ thread_func( latch ); }
> latch.wait();
> }
>
> private:
> void setup();
> void run();
>
> void thread_func( countdown_latch& latch )
> {
> setup();
> latch.count_down();
> // from here on latch is a dangling reference don't use
>
> run();
> }
>
> std::thread thread_;
> };
>
> Or is there something cleaner?
>
++ It reduce the size of the widget.
- dangling reference (but that can be mastered.

I don't know your constraints:
Why do you need to run the setup on the new created thread?
Could it be executed directly on the widget constructor?
If yes

class widget {
public:
     widget() {
         setup();
         thread_ = std::thread( [&]{ run( ); } );
     }
private:
     void setup();
     void run();
     std::thread thread_;
};

Do you need to manage the thread? if not, detaching the thread allows
you to don't include it on the widget context.

class widget {
public:
     widget() {
...
         std::thread( [&]{ thread_func( latch ); }).detach();
...
     }
private:
     void setup();
     void run();
};

Best,
Vicente


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