我见过很多多线程和锁的接口。
这些让我感到沮丧,
其中一些包含2个不同的类,如下面的示例,而
其他的只有一个类,而acquire()可以实现等待函数。
我的问题是:为什么我们在面向对象编程中设计这样的锁?
如何操作这样的对象?
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_;
};发布于 2009-06-07 19:18:23
上面是一个锁和一个条件变量。
这是两个独特的概念:
锁只是一个打开或关闭的单个原子锁。
条件变量(很难正确使用)需要一个锁才能正确实现,但需要维护一个状态(基本上是一个计数)。
有关“条件变量”的信息,请参阅:
http://en.wikipedia.org/wiki/Monitor_(synchronization)
基本上,条件变量是用于创建" Monitor“(也称为Monitor Regions)的低级原语。监视器是设计为供多个线程使用的代码区域(但通常是一个受控数量(在简单情况下是一个)),但仍然是多线程安全的。
下面是使用“条件变量”的一个很好的例子。
How to implement blocking read using POSIX threads
基本上允许2个线程进入监视器区域。一个线程正在从一个向量中读取数据,而另一个线程正在从该向量中读取数据。“Monitor”控制两个线程之间的交互。虽然仅仅使用锁就可以达到同样的效果,但是正确地使用它要困难得多。
发布于 2009-06-07 19:15:01
锁的目的是防止两个不同的处理线程同时修改相同的内存位置。
当一个线程锁定一个代码区域,而第二个线程进入相同的代码区域时,第二个线程将等待第一个线程释放它的锁,然后再执行代码。
https://stackoverflow.com/questions/962573
复制相似问题