Boost logo

Boost Users :

From: Tom Widmer (tom_usenet_at_[hidden])
Date: 2006-02-17 09:31:04


Dhanvi Kapila wrote:
> Hi :
> 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;
> };
> ------------------------------------------------------
> I appreciate all the help.. How do I know to check for thread-safety in
> a code ? Are there any documents? I have checked online and have some
> links, but havent found documents which provide examples and explain..
> such a document would be really useful.

That code goes against the whole point of synchronization primitives in
boost.threads - it makes it easy to write code that leaves a lock
unlocked, e.g. when an exception is thrown. Why not work with the
library rather than against it?

It will be threadsafe though, yes, since the scoped lock constructor
will have to lock global_mutex before assigning to lk. If two threads on
two CPUs run lock at the same time, they will create separate,
independent scoped_lock objects, and one will get the lock and unlock it
before the other one gets to assign lk, so there's no problem. It's
inefficient though due to the memory allocation - why do you want it?

Tom


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