www.pudn.com > reader-writer.rar > reader-writer.cpp
#include#include #include #include #include #include const int MaxProductNum=100;//一个线程允许消费的最大产品数 struct ThreadInfo{ //线程基本信息 int ThreadNum;//记录该线程的编号 char ThreadType;//记录该线程是生产者还是消费者 int ThreadSleepTime;//记录该线程的休眠时间 //Produce信息 int ProductAddr;//记录生产的产品所存放的缓冲区 int ProductProducedNum;//记录该产品要被消费的次数 //Consume信息 int ProductConsuming;//下一个要被消费的产品号 int ProductNum;//记录该线程要消费的产品数 int ProductConsumed[MaxProductNum];//记录该线程要消费的产品 ThreadInfo(){ //构造函数 ProductProducedNum=0; ProductConsuming=0; ProductNum=0; } }; const int MaxThreadNum=100;//允许的最大线程数 int ThreadNum=0;//实际的线程数 ThreadInfo Threads[MaxThreadNum];//线程信息数组 int* ThreadID;//指向一个用于存放线程号的数组,因为CreateThread()函数的参数是引用类型 int BufferNum;//存放产品的缓冲区数 const char *FileAddr="D:\\aaa\\ThreadInfo1.txt";//数据文件 int *Buffer_Critical;//缓冲区 bool *Has_Product;//记录相应缓冲区是否有产品,和Buffer_Critical及Produce()配合使用 HANDLE h_Semaphore[MaxThreadNum];//对应线程的信号量 HANDLE h_Full;//初始化为BufferNum,判断是否有空缓冲区 HANDLE h_Mutex;//用于分配缓冲区时互斥 HANDLE* h_Threads;//线程HANDLE 数组,存放各个线程的HANDLE void ReadTestInfoFile(){//读数据文件 ThreadInfo *ti; ifstream input_file; char ch; input_file.open(FileAddr,ios::binary); if(input_file){ if(input_file.get(ch)) BufferNum=ch-'0';//获得缓冲区数 input_file.get(ch); input_file.get(ch);//换行 do{ ti=&(Threads[ThreadNum++]); if(input_file.get(ch)) ti->ThreadNum=ch-'0'; if(input_file.get(ch));//读取线程号 if(input_file.get(ch)) ti->ThreadType=ch; if(input_file.get(ch));//读取线程类型 if(input_file.get(ch)) ti->ThreadSleepTime=ch-'0';//读取睡眠时间 if(ti->ThreadType=='P') input_file.get(ch); else if(ti->ThreadType=='C') while(input_file.get(ch)&&ch==' '){ input_file.get(ch); ti->ProductConsumed[ti->ProductNum++]=ch-'0'-1; } } while(input_file.get(ch)); } } void InitData()//统计数据,并初始化变量 { for(int i=0;i =Threads[j].ProductConsuming); } int GetProductID(int j)//取产品号,j为线程号 { int n=Threads[j].ProductConsuming++; return Threads[j].ProductConsumed[n]; } void Consume(int n)//消费,n为产品号 { Threads[n].ProductProducedNum--; } bool HasProductLeft(int n)//判断该产品是否还要消费,n为产品号 { return (Threads[n].ProductProducedNum>0); } void DeleteProduct(int n)//删除产品,n为产品号 { Has_Product[Threads[n].ProductAddr]=false; } void SleepTime(int t)//线程的睡眠时间函数(替代sleep系统函数) { for(;t>0;t--) for(long i=10000;i>0;i--) for(long j=10000;j>0;j--); } DWORD WINAPI Producer( LPVOID lpParam ) //生产者线程函数,lpParam是线程号 { int t=Threads[*(int*)lpParam].ThreadSleepTime; SleepTime(t); /**************/cout<<"ProducerThread: "<<*(int*)lpParam+1<<" Start"<