多生产者/消费者绩效

multi-producers/consumers performance

本文关键字:消费者 生产者      更新时间:2023-10-16

我写了一个SharedQueue,旨在与几个生产者/消费者一起工作。

class SharedQueue : public boost::noncopyable
{
public:
  SharedQueue(size_t size) : m_size(size){};
  ~SharedQueue(){};
  int count() const {return m_container.size();};
  void enqueue(int item);
  bool enqueue(int item, int millisecondsTimeout);
private:
  const size_t m_size;
  boost::mutex m_mutex;
  boost::condition_variable m_buffEmpty;
  boost::condition_variable m_buffFull;
  std::queue<int> m_container;
};
void SharedQueue::enqueue(int item)
{
  {
    boost::mutex::scoped_lock lock(m_mutex);
    while(!(m_container.size() < m_size)) 
    {
      std::cout << "Queue is full" << std::endl;
      m_buffFull.wait(lock);
    }
    m_container.push(item);
  }
  m_buffEmpty.notify_one();
}
int SharedQueue::dequeue()
{
  int tmp = 0;
  {
    boost::mutex::scoped_lock lock(m_mutex);
    if(m_container.size() == 0) 
    {
      std::cout << "Queue is empty" << std::endl;
      m_buffEmpty.wait(lock);
    }
    tmp = m_container.front();
    m_container.pop();
  }
  m_buffFull.notify_one();
  return tmp;
}

SharedQueue Sq(1000);

void producer()
{
  int i = 0;
  while(true)
  {
    Sq.enqueue(++i);
  }
}
void consumer()
{
  while(true)
  {
    std::cout  << "Poping: " << Sq.dequeue() << std::endl;
  }
}
int main()
{
  boost::thread Producer(producer);
  boost::thread Producer1(producer);
  boost::thread Producer2(producer);
  boost::thread Producer3(producer);
  boost::thread Producer4(producer);
  boost::thread Consumer(consumer);
  Producer.join();
  Producer1.join();
  Producer2.join();
  Producer3.join();
  Producer4.join();
  Consumer.join(); 
  return 0;
}

如您所见,我使用boost::condition_variable。有没有办法使性能更好?也许我应该考虑任何其他同步方法?

在真实场景而不是综合测试中,我认为您的实现已经足够好了。

但是,如果您预计每秒有 10 个6 个或更多操作,并且您正在为 Windows 进行开发,那么您的解决方案就不是那么好了。

  1. 在Windows上,当你使用多线程类时,Boost传统上非常糟糕。对于互斥锁,CriticalSection 对象通常要快得多。对于 cond.vars,Boost的作者正在重新发明轮子,而不是使用正确的Win32 API。

  2. 在 Windows 上,我希望名为"I/O 完成端口"的本机多生产者/使用者队列对象比任何可能的用户模式实现都有效几倍。它的主要目标是I/O,但是调用PostQueuedCompletionStatus API将您想要的任何内容发布到队列中是完全可以的。唯一的缺点 - 队列没有上限,因此您必须自己限制队列大小。

这不是对您的问题的直接回答,但可能是一个不错的选择。

根据您希望提高性能的程度,可能值得查看中断器模式:http://www.2robots.com/2011/08/13/a-c-disruptor/