读者写者问题实现操作系统课程设计 第5页

读者写者问题实现操作系统课程设计 第5页
wait_for_mutex=WaitForSingleObject(h_Mutex,-1);   //等待互斥信号,保证对readcount的访问、
               //修改互斥
 readcount++;                                      //读者数目加一
 if (readcount==1)
  EnterCriticalSection(&RP_Write);//禁止写者进入          
 ReleaseMutex(h_Mutex);//释放互斥对象,允许下个读者继续读:
 //读文件
 cout<<"读者线程 "<<m_Threadhao<<" 开始读文件."<<endl;
 Sleep(m_ThreadRunTime);
 //退出线程
 cout<<"读者线程 "<<m_Threadhao<<" 完成读文件."<<endl;
 wait_for_mutex=WaitForSingleObject(h_Mutex,-1);  //等待互斥信号,保证对readcount的访问、修改互斥
 readcount--;                                     //读者数目减少
 if (readcount==0)
  LeaveCriticalSection(&RP_Write);          //如果所有读者读完,唤醒写者
 ReleaseMutex(h_Mutex);//释放互斥信号
}
//读者优先-----写者线程
void R_WriterThread(void *p)
{
 DWORD m_delay;          //延迟时间
 DWORD m_ThreadRunTime;  //读文件持续时间
 int m_Threadhao;        //线程序号
 //从参数中获得信息
 m_Threadhao=((ThreadInfo *)(p))->Threadhao;
 m_delay=(DWORD)(((ThreadInfo *)(p))->ThreadStartTime*100);
 m_ThreadRunTime=(DWORD)(((ThreadInfo *)(p))->ThreadRunTime*100);
 Sleep(m_delay);                                   //延迟等待
 cout<<"写者线程 "<<m_Threadhao<<" 发出写请求."<<endl;
 EnterCriticalSection(&RP_Write);//禁止下一位写者进入
 //写文件
 cout<<"写者线程 "<<m_Threadhao<<" 开始写文件."<<endl;
 Sleep(m_ThreadRunTime);
 //退出线程
 cout<<"写者线程 "<<m_Threadhao<<" 完成写文件."<<endl;
 LeaveCriticalSection(&RP_Write); //如果所有读者读完,唤醒写者
}
//写者优先处理函数
void WriterFun(char* file)
{
 DWORD n_thread=0;        //线程数目
 DWORD thread_ID;         //线程ID
 DWORD wait_for_all;      //等待所有线程结束
 //互斥对象
 HANDLE h_Mutex1, h_Mutex2, h_Mutex3;
 h_Mutex1 = CreateMutex(NULL, FALSE, "mutex_for_writecount");
 h_Mutex2 = CreateMutex(NULL, FALSE, "mutex_for_readcount");
 h_Mutex3 = CreateMutex(NULL, FALSE, "mutex_for_read");
 //线程对象数组
 HANDLE h_Thread[64];
 ThreadInfo thread_info[64];
 readcount=0;     //初始化readcount
 InitializeCriticalSection(&cs_Write);  //初始化临界区
 InitializeCriticalSection(&cs_Read);
 ifstream inFile;
 inFile.open(file);                     //打开文件
 cout<<"写者优先:\n"<<endl;
 while (inFile)
 {//读入每一个读者、写者的信息  inFile>>thread_info[n_thread].Threadhao
>>thread_info[n_thread].ThreadClass
 >>thread_info[n_thread].ThreadStartTime
>>thread_info[n_thread].ThreadRunTime;
 if(-1 == inFile.get())
   break;
  n_thread++;//线程数加一
 }
 for (int i=0;i<(int)(n_thread);i++)
 {
  if (thread_info[i].ThreadClass=='r')
   //创建读者线程
   h_Thread[i]=CreateThread(NULL,0,\
   (LPTHREAD_START_ROUTINE)(W_ReaderThread),\
   &thread_info[i],0,&thread_ID);
  else
   //创建写者线程
   h_Thread[i]=CreateThread(NULL,0,\
   (LPTHREAD_START_ROUTINE)(W_WriterThread),\
   &thread_info[i],0,&thread_ID);
 }
 //等待所有线程结束
 wait_for_all=WaitForMultipleObjects(n_thread,h_Thread,TRUE,-1);
 cout<<"所有的读者和写者线程完成操作."<<endl;
}
//写者优先-----写者线程
void W_WriterThread(void *p)
{
 //互斥变量
 HANDLE h_Mutex1;
 h_Mutex1 = OpenMutex(MUTEX_ALL_ACCESS,FALSE,"mutex_for_writecount")

上一页  [1] [2] [3] [4] [5] [6] 下一页

Copyright © 2007-2012 www.chuibin.com 六维论文网 版权所有