簡體   English   中英

boost :: thread生產者使用者

[英]boost::thread producer consumer

我剛開始使用boost::thread我正在使用Monitor使生產者成為消費者。 到目前為止,這就是我編碼的方式。

//{ 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() 而且我不知道我該如何寫給消費者。 誰將擁有此生產者,消費者和監控者的所有權?

這樣可以嗎 ?

  1. 您不應將一個條件變量用於兩個不同的謂詞。 對隊列已滿條件使用一個條件變量,對隊列空條件使用一個條件變量,否則最終將缺少更新。

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

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

設計生產者和消費者取決於您,並且高度取決於您的要求。 生產者/使用者方案用於將工作負載的產生與實際處理分離。 這是工作的緩沖。

誰將擁有此生產者,消費者和監控者的所有權?

根據您的設計,可能有意義的是,生產者擁有隊列,而隊列擁有使用者。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM