|
Boost Users : |
From: Kevin Heifner (heifner_k_at_[hidden])
Date: 2006-02-17 11:21:14
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
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