Boost logo

Boost :

From: William E. Kempf (wekempf_at_[hidden])
Date: 2003-06-07 09:15:40


Stefan Seefeld said:
> Alexander Terekhov wrote:
>> This is far from elegant, because the queue data structure already
>> knows the number of messages either implicitly or with an extra
>> counter of its own.
>
> well, I need to know it explicitely when I want to extract the next one,
> so either the queue caches its length, or I have to count each time.
>
>> Usually, what is most relevant is whether or not the queue is empty.
>> So the semaphore is coding redundant information. Note that at times,
>> this information will be out of sync. For example, say you have
>> this sequence of actions:
>>
>> lock();
>> append(item);
>> unlock();
>> signal(semaphore);
>>
>> In between the append and signal operation, the queue has N+1 items,
>> but the semaphore's value is out of date at N.
>
> so what ? the 'real' queue length is kept private and doesn't matter
> much. It's the signaling of the semaphore that makes the change public.

This is a race condition. It also occurs when extracting data from the
queue. Whether or not the "'real' queue length" is private is not
relevant, this race condition can lead to improper synchronization, such
as trying to to extract data when there's no data left to extract.

>> A semaphore has an internal lock which protects incremnts and
>> decrements of its internal counter. There is no way to extend that
>> lock to cover additional data such as a queue. With a mutex and
>> condition variable, the entire queue can be treated as a semaphore
>> based on its *own* state!
>
> I never said it can't. Besides, I'd like to argue about your description
> of the implementation of semaphores. There is no need for a lock around
> the internal counter, if the semaphore is implemented with atomic
> counters. Of course, that's true only on platforms that support atomic
> counters...

That's still a form of a lock.

> And then there is the other semaphore I use to count the free slots,
> which you didn't comment on, probably because it didn't fit into your
> arguments...

No, actually, it strengthens the argument, because you now have even more
state that needs to be synchronized to ensure against race conditions.

> This is my last mail in this thread. It's not related to boost any more
> anyways. We have to agree to disagree.

If you want semaphores to be added to Boost.Threads, the arguments are
very much on topic here.

-- 
William E. Kempf

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