Boost logo

Boost :

Subject: Re: [boost] [thread] synchronized_value: value and move semantics
From: Ben Pope (benpope81_at_[hidden])
Date: 2013-06-26 22:58:37


On 27/06/13 01:05, Vicente J. Botet Escriba wrote:
> Le 26/06/13 18:03, Vicente Botet a écrit :
>> Ben Pope wrote
>>> I can see the usefulness of synchronized_value for C++03, but not in
>>> C++11.
>> Why?
>>
>>
>>> It's just too easy to forget to call the synchronise() member:
>>>
>>> boost::synchronized_value<std::queue<int>> synch_queue;
>>> if(!synch_queue->empty())
>>> synch_queue->pop();
>>>
>>> when was was meant was (excuse use of auto, I've become lazy):
>>>
>>> boost::synchronized_value<std::queue<int>> synch_queue;
>>> {
>>> auto lock = synch_queue.synchronize();
>>> if(!synch_queue->empty())
>>> synch_queue->pop();
>>> }
>>>
>>> This is neither safe or efficient (2 lock/unlocks).
>> this should be
>>
>> boost::synchronized_value<std::queue<int>> synch_queue;
>> {
>> auto lock = synch_queue.synchronize();
>> if(!lock->empty())
>> lock->pop();
>> }

OK, I should have paid more attention to detail, my apologies.

I think it's just a little bit too easy to forget to use the stack based
lock, especially during code maintenance and moving from one call to
more than one call.

>>> I think this should just not exist in C++11 and instead be replaced by
>>> something like monitor
>>> <T>
>>> described by Herb Sutter [1]:
>>>
>>> monitor&lt;std::queue&lt;int&gt;> synch_queue;
>>> queue([](std::queue& q)
>>> {
>>> if(!q.empty())
>>> q.pop();
>>> }
>> Sorry I don't understand the syntax.
>>
> After looking at the slides I understand now what it means.
> I guess you meant
>
> sync_queue([](std::queue& q)
>
> {
> if(!q.empty())
> q.pop();
> }
> );

D'oh! Always compile example code. My bad.

> I like execute around a function locking pattern, and yes without
> lambdas this pattern is not practical, so no portable to C++03.
> Adding the function to synchronized_value would not be too hard.

I'd settle for that, with a note that's it's preferable in C++11 :)

Thanks.

Ben


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