Boost logo

Boost Users :

From: William E. Kempf (wekempf_at_[hidden])
Date: 2003-05-11 14:30:27


Peter G said:
> hi there...
>
> what is the scope of locked variables? assuming that i declare a mutex
> in say a class scope.. and then lock it in some inner scope - say in a
> function.. what variables get locked? is it all the variables which are
> in the scope of the declaration (ie all the variables which are declared
> in the class)? or is it only the ones which are being used in that
> particular function (so that perhaps another thread could use the rest
> at "the same time")?
>
> for example:
>
> class Class1
> {
> public:
>
> Class1::Class1();
> ~Class1::Class1();
>
> void f(int new)
> {
> boost::mutex::scoped_lock scoped_lock(mutex_outer) ;
> var1 = new;
> }
>
> void g(int new)
> {
> boos::mutex mutex_inner;
> boost::mutex::scoped_lock scoped_lock(mutex_inner) ;
> var1 = new;
> }
> private:
>
> boost::mutex mutex_outer;
> Class2 some_member_object;
> int var1;
> int var2;
> };
>
> what gets locked when f() is called?

The "mutex_outer" variable, nothing more, nothing less.

> when should i use g()?

Never, because it's invalid C++ ;).

But seriously, fix the syntax problems and I'd still say never. Every
time g() is called you get a new "mutex_inner", so the lock is pointless.

> how do I go about just locking say var1 but NOT var2?

You don't lock variables, you lock mutexes. What variables a mutex
protects is a logical part of the code, not something enforced by the
syntax/semantics. IOW, the mutex protects only what you want it to
protect, nothing more, nothing less, and any coding errors on your part
can lead to race conditions because you've failed to live up to the
logical contract *you* specified for the mutex.

At this point things are so confused, I'm not sure how to word things so
that I don't confuse you more. If you think a variable should be
protected by a mutex, *always* lock that mutex before using the variable.
If not, then realize the variable is not protected and should not be
accessed from multiple threads. Protecting a variable with multiple
mutexes is also a very bad idea, and will result in race conditions or
deadlock in most cases (and inefficient code in the other cases).

> if i lock the mutex in this class scope, does that mean that all the
> variables in some_member_object are locked as well?

Only if you consider them to be.

> also, should i set up locks anytime i am using an object which might be
> accesses by another thread (even if I am just reading it) or is it
> enough to only lock variables when i am changing them?

No, locking only when you write is not enough. Fail to lock when you read
and you may read data that's only partially "correct", i.e. the invariants
may be broken.

-- 
William E. Kempf

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net