Boost logo

Boost :

Subject: Re: [boost] [thread] upgrading read lock to write lock
From: Howard Hinnant (howard.hinnant_at_[hidden])
Date: 2011-02-06 18:51:30


On Feb 6, 2011, at 5:10 PM, Peter Dimov wrote:

> Howard Hinnant wrote:
> ...
>> int main()
>> {
>>
>> ting::upgrade_mutex m;
>> ting::upgrade_lock<ting::upgrade_mutex> readlock(m);
>> // reads go here
>
> The problem is that only one thread can do this at a time, and I suspect that in the original problems, there are many such readers, some of which need to then write, but only occasionally. This is one way to do it:
>
> take read lock;
> int v = data.version_;
> // reads go here
> drop read lock;
>
> if( need to write )
> {
> take write lock;
>
> if( v != data.version_ )
> {
> retry reads;
> }
>
> if( still need to write )
> {
> ++data.version_;
> // writes go here
> }
>
> drop write lock;
> }
>
> Note that no upgrade locks are needed.

Yes, there are several tools in the tool box here. And none of them are the right tool for all situations. The upgradable lock tends to be most needed when the read is expensive enough that you want to put extra effort into not repeating it.

-Howard


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