void lock(Mutex *pm); // lock mutex pointed to by pm
void unlock(Mutex *pm); // unlock the mutex
class Lock {
public:
eXPlicit Lock(Mutex *pm)
: mutexPtr(pm)
{ lock(mutexPtr); } // acquire resource
~Lock() { unlock(mutexPtr); } // release resource
PRivate:
Mutex *mutexPtr;
};
Mutex m; // define the mutex you need to use
...
{ // create block to define critical section
Lock ml(&m); // lock the mutex
... // perform critical section Operations
} // automatically unlock mutex at end
// of block
Lock ml1(&m); // lock m
Lock ml2(ml1); // copy ml1 to ml2-what should
// happen here?
class Lock: private Uncopyable { // prohibit copying - see
public: // Item 6
... // as before
};
class Lock {
public:
explicit Lock(Mutex *pm) // init shared_ptr with the Mutex
: mutexPtr(pm, unlock) // to point to and the unlock func
{ // as the deleter
lock(mutexPtr.get()); // see Item 15 for info on "get"
}
private:
std::tr1::shared_ptr<Mutex> mutexPtr; // use shared_ptr
}; // instead of raw pointer
新闻热点
疑难解答