Boost logo

Boost Users :

From: Malte Clasen (news_at_[hidden])
Date: 2006-02-17 05:13:03


Dhanvi Kapila wrote:
> I have this piece of code for mutex operations. is this code
> thread-safe ? I plan to use this code in threads...
> ------------------------------------
> class BoostMutexLock
> {
> public :
> void lock() {
> lk = new boost::mutex::scoped_lock(global_mutex);
> }
> void unlock() {
> delete lk;
> }
> BoostMutexLock() : lk( 0 ) { }
> ~BoostMutexLock() { }
>
> private:
> boost::mutex global_mutex;
> boost::mutex::scoped_lock* lk;
> };
> ------------------------------------------------------

That depends on how you want to use this object. I assume that you want
to share it between threads since there's no way to let two locks use
the same mutex with this design. If this is the case, check out
http://www.boost.org/doc/html/threads/concepts.html#threads.concepts.lock-concepts
and
http://www.boost.org/doc/html/threads/rationale.html#threads.rationale.locks

Let's assume that you have two threads. Thread A has already locked the
shared BoostMutexLock when B tries to do the same. Now B waits until the
mutex is unlocked. As soon as A calls unlock(), the lock object is
destroyed and the mutex unlocked. Now it might happen that before the
lock pointer is deleted, B is started and creates a new lock object,
overwriting lk. The memory of the previous lock object is leaked. After
that, A deletes lk, so the mutex is unlocked again while B is inside the
protected section.

      Malte


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