2009-06-07 77 views
0

我已经看到了多种多线程和锁的接口。如何操作这个界面?

这让我感到沮丧,

一些包括2个不同的类,如下面的示例,而

别人只有一个类和获取()可以实现等待功能。

我的问题是: 为什么我们在面向对象编程中设计这样的锁?

如何操作这些对象?

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_; 
}; 

回答

1

上面是一个锁和一个条件变量。
这些是两个独特的概念:

锁只是一个单一的原子锁打开或关闭。

一个条件变量(很难正确使用)并且需要一个锁来正确实现,但保持一个状态(基本上是一个计数)。

有关“条件变量”信息,请参阅:
http://en.wikipedia.org/wiki/Monitor_(synchronization)

基本条件变量是用于创建“监视”(又名监视器地区)低级原语。监视器是设计用于多线程的代码区域(但通常是一个受控数字(在简单的情况下是一个)),但仍然是多线程安全的。

以下提供了一个使用'条件变量'的好例子。
How to implement blocking read using POSIX threads

基本上2个线程被允许进入监控区域。一个线程正在从矢量读取,而另一个线程正在从矢量中读取数据。 'Monitor'控制2个线程之间的交互。虽然使用锁可以达到同样的效果,但要正确地做到这一点非常困难。

1

锁的目的是防止两个不同的处理线程从在同一时间修改相同的存储器位置。

当一个线程锁定一段代码,并且第二个线程进入相同的代码区域时,第二个线程将在执行代码之前等待第一个线程释放其锁定。