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-co... 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