Boost logo

Boost Users :

From: Emre Birol (ebirol_at_[hidden])
Date: 2006-02-17 12:38:36


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.
>
> Thanks...
> Dhanvi

This code is against to RAII (Resource Allocation Is Initialization)
idiom.

Would be better if you use it that way:

try {
        boost::mutex::scoped_lock(global_mutex);
        ...
        <your code here>
}
catch {
        
}

if you don't need to use try-catch then just add a scope:

{
        boost::mutex::scoped_lock(global_mutex);
        ...
        <your code here>

}

It's guarantied that mutex will be released when execution leaves the scope.


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