Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/138.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ boost::线程生产者消费者_C++_Boost_Boost Thread_Producer Consumer - Fatal编程技术网

C++ boost::线程生产者消费者

C++ boost::线程生产者消费者,c++,boost,boost-thread,producer-consumer,C++,Boost,Boost Thread,Producer Consumer,我是新来的boost::thread。到目前为止,我就是这样编码的 //{ Declarations in header private: boost::condition_variable _condition; boost::mutex _mutex; std::deque<RawMatrix*> _queue; boost::detail::atomic_count _count; //} void Matr

我是新来的
boost::thread
。到目前为止,我就是这样编码的

//{ 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;
}
但是我应该如何在某个时间间隔内运行
product()
。我不知道我需要在《消费者》杂志上写些什么。谁将拥有这个生产者、消费者和监测仪的所有权

可以吗

  • 不应该对两个不同的谓词使用一个条件变量。将一个条件变量用于队列已满条件,将一个条件变量用于队列已空条件,否则将导致缺少更新

  • 在product()函数中,如果没有必要,则不应锁定第二个互斥锁。如果它是调用rawMatrix()的必要谓词,那么至少可以在调用deposit()之前释放互斥体,以不锁定两个互斥体。每次锁定多个互斥锁时,必须注意可能存在的死锁。避免死锁的一种方法是始终以相同的顺序锁定互斥锁(所谓的锁层次结构)

  • 我现在如何设计生产者和消费者

    设计您的生产者和消费者取决于您,高度依赖于您的需求。生产者/消费者模式用于将工作负载的产生与实际处理解耦。它是工作的缓冲区

    谁将拥有该生产商、消费者和监视器的所有权


    根据您的设计,生产者拥有队列,队列拥有消费者可能是有道理的。

    如果我在调用
    rawMatrix()
    之前解锁互斥体,我是否仍然需要锁定
    rawMatrix()
    中的互斥体?当然,是rawMatrix()中的互斥体存在保护队列和计数不受其他线程看到它们处于不一致状态的影响。
    void MatrixProducer::produce(){
        boost::mutex::scoped_lock lock(_mutex);
        RawMatrix* matrix = rawMatrix();
        _monitor->deposit(matrix);
    }
    RawMatrix* MatrixProducer::rawMatrix(){/*Generates and returns a matrix*/}