|
Boost : |
From: Tanguy Fautre (tanguy.fautre_at_[hidden])
Date: 2007-03-02 05:47:51
Stefan Seefeld wrote:
> Philippe Vaucher wrote:
>> Hello,
>>
>> Well, the subject says it all ;)
>> This question comes because boost::signal's documentation says it's not
>> thread safe, but I have trouble finding exactly why it isn't.
>>
>> Let's look the following example:
>>
>> Each thread is connected to the same signal, then the signal is emmited, and
>> each threads receives the message.... Why would this not be thread safe ?
>
> You use 'thread' in a very lose way here. There is a 'thread' as seen by the
> OS, i.e. an execution entity processing some code, and there is are two
> 'thread' types ('thread1' and 'thread2') you use.
>
> In your description above you seem to refer to those types as 'threads',
> not to the execution entities.
>
> The point is, the 'threads of execution' don't 'receive the message', as
> the 'slot()' methods are executed in the main thread. However, as you check
> the value of 'finished' in other 'threads of execution', you have to protect
> access to it by a mutex. For example:
>
> struct thread1
> {
> thread1() : finished_(false) {}
> void operator()()
> {
> while (true)
> {
> scoped_lock lock(mutex_);
> if (finished_) return;
> }
> }
> void slot()
> {
> scoped_lock lock(mutex_);
> finished_ = true;
> }
>
> bool fininshed_;
> mutex mutex_;
> };
>
>
> HTH,
> Stefan
>
I'm not sure whether a mutex is really needed here. Because a boolean is
a native type, I don't see any particular problem if one thread reads it
while it's being written by another.
So I think the mutex can be safely removed.
What I would however do is to use "volatile bool" instead of just "bool"
Tanguy
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk