
Tom Widmer wrote:
Dhanvi Kapila wrote:
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; }; ------------------------------------------------------
[snip]
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?
I don't think it is threadsafe on every platform. It it my understanding that the following line: lk = new boost::mutex::scoped_lock(global_mutex); can be split by the compiler to be: lk = malloc(sizeof(boost::mutex::scoped_lock)); // alloc and assign // another thread could come in here, causing // leak of the first malloc and a later double // delete lk->boost::mutex::scoped_lock(global_mutex); // call constructor See, for example: http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html for more info. KevinH -- Kevin Heifner heifner @ ociweb.com http://heifner.blogspot.com Object Computing, Inc. (OCI) www.ociweb.com