$include_dir="/home/hyper-archives/boost/include"; include("$include_dir/msg-header.inc") ?>
From: William Kempf (sirwillard_at_[hidden])
Date: 2000-09-14 09:16:56
--- In boost_at_[hidden], Levente Farkas <lfarkas_at_m...> wrote:
> hi,
> I find an example where lock and unlock can be useful.
> suppose we'd like to protect a with m, but we don't would like to 
protect f
> (suppose it's long) and have the following code (if we have 
lock/unlock on 
> mutex).
> -----------
> {
>   boost::lock lock(m);
>   for (int i = a.get(); i < 10; a.next())
>   {
>     <some code>
>     m.unlock()
>     f();
>     m.lock();
>     <some code>
>   }
> }
> -----------
> without lock/unlock is looks like:
> -----------
> {
>   {
>     boost::lock lock(m);
>     int i = a.get();
>   }
>   while (i < 10)
>   {
>     <some code>
>     f();
>     <some code>
>     {
>       boost::lock lock(m);
>       a.next();
>       i = a.get();
>     }
>   }
> }
> -----------
> IMHO the first version is more simple clear and easier to read and 
understand.
Purely opinion.  Personally, I don't agree.
In any event this example likely leads to a race condition!  f() may 
modify a in a way that will invalidate the call to next()!  
(Arguments that it doesn't don't hold water with me, since later 
maintenance may change that.)
There are numerous ways to refactor this example, and it really needs 
refactoring.  Probably the safest solution is to take a hint from 
Java here and "enumerate" a by taking a (thread safe) snapshot of it 
in a locally controlled copy which can be safely iterated over, even 
if a were to be modified by f().
My point?  Writing thread safe code is very difficult, and your 
attempt to show an example of why lock/unlock might be useful helps 
to illustrate this fact.  With out the lock/unlock a programmer is 
more likely to think about and analyze the problem for more 
appropriate solutions before jumping to a lock/unlock idiom that 
results in race conditions or even deadlocks.  And again, if you 
*must* do this you still can, using constructs such as the 
unsafe_lock<> I posted.
Sorry, you've not convinced me to expose the lock/unlock on the Mutex 
concept.
> create the lock on the heap can't help here.
And why not?
Bill Kempf