I have seen lots of kinds of interface to multithreading and locks.
These make me feel frustrating,
Some of them include 2 different classes like the sample below, while
others have only one class and the acquire() can implement the wait function.
My questions are: Why we design locks like this in object oriented programming?
How to manipulate such objects?
class Lock
{
public:
Lock();
~Lock();
// Acquire the lock.
void
acquire()
{ this->lock_->acquire(); }
// Release the lock.
void
release()
{ this->lock_->release(); }
private:
// This class can not be copied.
Lock(const Lock&);
Lock& operator=(const Lock&);
friend class Condvar;
Lock_impl*
get_impl() const
{ return this->lock_; }
Lock_impl* lock_;
};
class Condvar
{
public:
Condvar(Lock& lock);
~Condvar();
// Wait for the condition variable to be signalled. This should
// only be called when the lock is held.
void
wait()
{ this->condvar_->wait(this->lock_.get_impl()); }
// Signal the condition variable--wake up at least one thread
// waiting on the condition variable. This should only be called
// when the lock is held.
void
signal()
{ this->condvar_->signal(); }
// Broadcast the condition variable--wake up all threads waiting on
// the condition variable. This should only be called when the lock
// is held.
void
broadcast()
{ this->condvar_->broadcast(); }
private:
// This class can not be copied.
Condvar(const Condvar&);
Condvar& operator=(const Condvar&);
Lock& lock_;
Condvar_impl* condvar_;
};