Boost logo

Boost :

From: Douglas Gregor (gregod_at_[hidden])
Date: 2001-05-23 16:01:37


On Wednesday 23 May 2001 13:21, you wrote:
[snip]
> >The reason to bother is to attain the optimal granularity of lock
> >(and an "application mutex" might not fit that bill either). A
> >threading library can't predict what level of granularity is optimal
> >since it's going to depend on the application, so such a type just
> >isn't appropriate.
> >
> >Beyond that, there's a severe problem with a
> >thread_safe_int_least32_t that behaves as an int. The level of
> >granularity of such a lock can actually lead to errors in usage. For
> >example:
> >
> >thread_safe_int_least32_t i = 10;
> >i = (i + 2) / 2;
> >
> >The above expression should be executed "atomically" (as in no other
> >thread can change the value of 'i' while the expression is being
> >evaluated) but it is not. The internal mutex is only locked during
> >the call to a single operation, so it's possible for another thread
> >to interrupt and change the value of 'i' in between the '+' and
> >the '/'. It can even interrupt before the assignment! This is why
> >atomic_t has very specific functions that can be called such as inc()
> >and dec() and doesn't have overloaded operators such as '++' and '--'.
>
> So reduce it to functions which can be safely provided.
>
> The point is to give programmers a nice palette of mid and hi level tools,
> not just the very low level ones. Jens Maurer's bounded queue was a good
> example.
>
> --Beman

Perhaps not in a first release of the threads library, but one could use
expression templates to make "i = (i+2)/2" safe. Delay evaluation until an
assignment operation is reached. On assignment it acquires a lock, performs
the evaluation and assignment, and then releases the lock.

        Doug


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