2012-07-27 256 views
1

我是boost::thread的新手我正在使用顯示器製造消費者。這是我迄今爲止的編碼。boost ::線程生產者消費者

//{ Declarations in header 
private: 
    boost::condition_variable _condition; 
    boost::mutex     _mutex; 
    std::deque<RawMatrix*>  _queue; 
    boost::detail::atomic_count _count; 
//} 

void MatrixMonitor::deposit(RawMatrix* rawMatrix){ 
    boost::unique_lock<boost::mutex> lock(_mutex); 
    _condition.wait(lock, boost::bind(std::less_equal<int>(), boost::ref(_count), max)); 
    _queue.push_back(rawMatrix); 
    ++_count; 
    _condition.notify_one(); 
} 

RawMatrix* MatrixMonitor::withdraw(){ 
    boost::unique_lock<boost::mutex> lock(_mutex); 
    _condition.wait(lock, boost::bind(std::greater_equal<int>(), boost::ref(_count), min)); 
    RawMatrix* elem = _queue.front(); 
    _queue.pop_front(); 
    --_count; 
    _condition.notify_one(); 
    return elem; 
} 

這樣好嗎?有一件事我不明白的是我現在怎麼設計製作人和消費者?到目前爲止,我已經做了

void MatrixProducer::produce(){ 
    boost::mutex::scoped_lock lock(_mutex); 
    RawMatrix* matrix = rawMatrix(); 
    _monitor->deposit(matrix); 
} 
RawMatrix* MatrixProducer::rawMatrix(){/*Generates and returns a matrix*/} 

但如何才能/我應該在運行某個區間的produce()。我不知道我需要在消費者中寫什麼。誰將擁有這個生產者,消費者和監督者的所有權?

回答

0

這樣好嗎?

  1. 你不應該使用一個條件變量的兩個不同的謂詞。對於隊列滿條件使用一個條件變量,而對於隊列空條件使用一個條件變量,否則最終會丟失更新。

  2. 在您的produce()函數中,如果沒有必要,您不應該鎖定第二個互斥鎖。如果這是調用rawMatrix()的必要謂詞,那麼在調用deposit()以不鎖定兩個互斥鎖之前,至少可以釋放互斥鎖。每次鎖定多個互斥鎖時,都必須注意可能的死鎖。避免死鎖的一種方法是始終以相同的順序鎖定互斥鎖(即所謂的鎖定層次結構)。

我會如何設計現在的生產者和消費者?

設計你的生產者和消費者是由你自己決定的,並且高度依賴於你的要求。生產者/消費者模式用於將工作負載的產生與實際處理分離。這是一個工作的緩衝區。

誰擁有這臺生產者,消費者和監視器?

根據您的設計,生產者擁有隊列和隊列擁有消費者可能是有道理的。

+0

如果我在調用'rawMatrix()'之前解鎖互斥鎖,是否仍然需要鎖定'rawMatrix()'內部的互斥鎖? – 2012-08-01 16:10:52

+0

當然,rawMatrix()裏面的互斥體是爲了保護_queue和_count,以防其他線程在不一致的狀態下看到它們。 – 2012-08-01 16:37:10