我编写了一个 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。有没有办法让性能更好?也许我应该考虑任何其他同步方法?