线程之路六:读者写者的问题

来源:互联网 发布:江苏政务数据资源网 编辑:程序博客网 时间:2024/06/06 07:16
//有一个写者很多读者,多个读者可以同时读文件,但写者在写文件时不允许有读者在读文件,同样有读者在读文件时写者也不去能写文件。#include <istream>#include <Windows.h>#include <process.h>CRITICAL_SECTION gcs,buffer;HANDLE readerover,writerover;int m=0;//读者数量BOOL SetConsoleColor(WORD wAttributes){HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);if (hConsole == INVALID_HANDLE_VALUE)return FALSE;return SetConsoleTextAttribute(hConsole, wAttributes);}//读者线程输出函数void readprint(char *pszformat,...){va_list p;va_start(p,pszformat);EnterCriticalSection(&gcs);vfprintf(stdout,pszformat,p);LeaveCriticalSection(&gcs);va_end(p);}//写者线程输出函数void writerprint(char* psz){EnterCriticalSection(&gcs);SetConsoleColor(FOREGROUND_GREEN);printf("     %s\n",psz);SetConsoleColor(FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE);LeaveCriticalSection(&gcs);}//写者unsigned int __stdcall writer(LPVOID pm){writerprint("写者等待……");WaitForSingleObject(readerover,INFINITE);ResetEvent(writerover);writerprint("写者写数据开始……");Sleep(rand()%100);writerprint("写者写数据完毕……");SetEvent(writerover);return 0;}//读者unsigned int __stdcall reader(LPVOID pm){readprint("     编号为%d的读者进入等待中...\n", GetCurrentThreadId());WaitForSingleObject(writerover,INFINITE);EnterCriticalSection(&buffer);m++;if (m ==1)ResetEvent(readerover);LeaveCriticalSection(&buffer);readprint("     编号为%d的读者读文件...\n", GetCurrentThreadId());Sleep(rand()%100);readprint("     编号为%d的读者读文件结束...\n", GetCurrentThreadId());EnterCriticalSection(&buffer);m--;if (m ==0) SetEvent(readerover);LeaveCriticalSection(&buffer);return 0;}void main(){InitializeCriticalSection(&buffer);InitializeCriticalSection(&gcs);readerover = CreateEvent(NULL,FALSE,TRUE,NULL);writerover = CreateEvent(NULL,TRUE,TRUE,NULL);//第二个参数手动置位事件相当于教室门,教室门一旦打开(被触发),所以有人都可以进入直到老师去关上教室门(事件变成未触发)。自动置位事件就相当于医院里拍X光的房间门,门打开后只能进入一个人,这个人进去后会将门关上,其它人不能进入除非门重新被打开(事件重新被触发)。HANDLE han[10];for (auto i =0;i<2;i++){han[i] = (HANDLE) _beginthreadex(NULL,0,reader,NULL,0,NULL);}han[2] =(HANDLE) _beginthreadex(NULL,0,writer,NULL,0,NULL);Sleep(50);for (auto i =3;i<10;i++){han[i] = (HANDLE) _beginthreadex(NULL,0,reader,NULL,0,NULL);}HANDLE han1[10];han1[2] =(HANDLE) _beginthreadex(NULL,0,writer,NULL,0,NULL);Sleep(100);for (auto i =0;i<2;i++){han1[i] = (HANDLE) _beginthreadex(NULL,0,reader,NULL,0,NULL);}for (auto i =3;i<10;i++){han1[i] = (HANDLE) _beginthreadex(NULL,0,reader,NULL,0,NULL);}WaitForMultipleObjects(10,han1,TRUE,INFINITE);for (auto i =0;i<10;i++){CloseHandle(han[i]);CloseHandle(han1[i]);}CloseHandle(readerover);CloseHandle(writerover);DeleteCriticalSection(&gcs);DeleteCriticalSection(&buffer);system("pause");}


 

0 0
原创粉丝点击