今天用两种方法实现了生产者消费者问题。第一种是高效的双缓冲队列,例外一种想法较为复杂,最终效果不如双缓冲队列。
写代码中无意中发现queue是不能用迭代器访问的,而且stack也不可以。
直接上代码如下:
DoubleQueue.h双缓冲队列,其中MutexLock MutexLockGuard见文章多线程读写数据方法之读写锁方法与shared_ptr+互斥锁方法的比较
#ifndef DOUBLEQUEUE_H_INCLUDED
#define DOUBLEQUEUE_H_INCLUDED
#include<unistd.h>
#include<pthread.h>
#include<boost/shared_ptr.hpp>
#include<queue>
#include<fstream>
#include<cstdlib>
using namespace std;
#include"MutexLock.h"
#include"MutexLockGuard.h"
#include"Condition.h"
#include"MaxSizeQueue.h"
class DoubleQueue{
private:
vector<BufferLog> q1;
vector<BufferLog> q2;//1是写队列2是读队列
MutexLock mutex1_,mutex_2;
FILE* file;
public:
DoubleQueue(){
file= fopen("out","w");
}
void EnQueue(const BufferLog& log){
MutexLockGuard lock(mutex1_);
q1.push_back(log);
}
bool DeQueue(int done,int all,BufferLog* logs){//单线程写,不对q2的使用加锁了
if(q2.empty()){
MutexLockGuard lock(mutex1_);
q1.swap(q2);
}
if(done==all&&q2.empty()){
fclose(file);
return true;
}
for(vector<BufferLog>::iterator p=q2.begin();p!=q2.end();++p){
fprintf(file,"%d %d\n",(int)p->type,p->cnt);
logs[(int)p-&g