2009-06-07 78 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

鎖的目的是防止兩個不同的處理線程從在同一時間修改相同的存儲器位置。

當一個線程鎖定一段代碼,並且第二個線程進入相同的代碼區域時,第二個線程將在執行代碼之前等待第一個線程釋放其鎖定。