多生产者/消费者绩效
multi-producers/consumers performance
我写了一个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 进行开发,那么您的解决方案就不是那么好了。
-
在Windows上,当你使用多线程类时,Boost传统上非常糟糕。对于互斥锁,CriticalSection 对象通常要快得多。对于 cond.vars,Boost的作者正在重新发明轮子,而不是使用正确的Win32 API。
-
在 Windows 上,我希望名为"I/O 完成端口"的本机多生产者/使用者队列对象比任何可能的用户模式实现都有效几倍。它的主要目标是I/O,但是调用PostQueuedCompletionStatus API将您想要的任何内容发布到队列中是完全可以的。唯一的缺点 - 队列没有上限,因此您必须自己限制队列大小。
这不是对您的问题的直接回答,但可能是一个不错的选择。
根据您希望提高性能的程度,可能值得查看中断器模式:http://www.2robots.com/2011/08/13/a-c-disruptor/
相关文章:
- 消费者和生产者问题的双重缓冲
- 如何降低生产者获得锁的可能性,而消费者在使用std::condition_variable时无法获得锁?
- C++ deque 消费者总是从生产者那里得到空队列
- C++多线程生产者-消费者问题
- 生产者和消费者优化
- 特定的生产者-消费者方案
- 为什么condition_variable在等待生产者-消费者的锁定?C++
- 将生产者/消费者与障碍同步
- 单个生产者/多个消费者死锁
- 带有共享缓冲区的两个等待线程(生产者/消费者)
- C++简单的消费者生产者问题
- 生产者/消费者,消费者线程从未执行过
- 在使用 pthread 和信号量实现生产者-消费者问题时需要帮助
- 如何在 c++ 中使用 winapi 事件解决生产者-消费者
- C++生产者消费者陷入僵局
- 简单生产者和消费者的unique_lock困难
- 生产者消费者实现中的条件变量应如何初始化
- 如何实现消费者生产者,消费者可以请求新的数据
- c++中的消费者/生产者
- 如何同步线程(消费者/生产者)