我编写了一个 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。有什么办法可以让性能变得更好吗?也许我应该考虑任何其他同步方法?
最佳答案
在真实场景而不是综合测试中,我认为您的实现足够好。
但是,如果您期望每秒执行 106 或更多操作,并且您正在为 Windows 进行开发,那么您的解决方案就不是那么好。
在 Windows 上,当您使用多线程类时,Boost 传统上非常糟糕。 对于互斥体,CriticalSection 对象通常要快得多。对于条件变量, boost 的作者正在重新发明轮子,而不是使用 correct Win32 API .
在 Windows 上,我期望称为“I/O 完成端口”的 native 多生产者/消费者队列对象比任何可能的用户模式实现有效数倍。它的主要目标是 I/O,但是调用 PostQueuedCompletionStatus API 是完全可以的。将您想要的任何内容发布到队列中。唯一的缺点 - 队列没有上限,因此您必须自己限制队列大小。
关于c++ - 多生产者/消费者绩效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13573252/