这是使用VS 2010并发队列的典型生产者/消费者模式,问题是当我运行程序时,内存消耗超过1GB然后程序崩溃,有人可以指出这段代码中的问题吗?
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <boost\shared_ptr.hpp>
#include <boost\thread.hpp>
#include <concurrent_queue.h>
void wait2(int milliseconds)
{
boost::this_thread::sleep(boost::posix_time::milliseconds(milliseconds));
}
class CQueue
{
Concurrency::concurrent_queue<int> Q;
boost::mutex m;
boost::condition_variable cv;
public:
CQueue():QValue(-1)
{
}
int QRead()
{
while(Q.empty())
{
boost::unique_lock<boost::mutex> lk(m);
cv.wait(lk);
}
int res;
if(Q.try_pop(res))
{
QValue = res;
return true;
}
return false;
}
void QWrite(int i)
{
Q.push(i);
cv.notify_one();
}
int QValue;
};
CQueue myqueue;
void write()
{
int i = 0;
while(true)
{
myqueue.QWrite(++i);
}
}
void read()
{
while(true)
{
if( myqueue.QRead())
std::cout << myqueue.QValue << std::endl;
else
std::cout << "failed to read" << std::endl;
}
}
void main ()
{
boost::thread w(write);
boost::thread r(read);
w.join();
r.join();
}