c++初步实现:
- // 读者写者.cpp : 定义控制台应用程序的入口点。
- //
- #include "stdafx.h"
- #include <iostream>
- #include <Windows.h>
- using namespace std;
- const int readerNum=5;
- const int writerNum=5;
- const int readerSleep=100;
- const int writerSleep=100;
- const int waittime=100;
- static int nr=0;
- static int nw=0;
- static int readerCount=0;
- HANDLE mutex;
- HANDLE db;
- void acquireReadLock(){
- WaitForSingleObject(mutex,waittime);
- ++readerCount;
- if(readerCount==1)
- WaitForSingleObject(db,waittime);
- ReleaseMutex(mutex);
- }
- void releaseReadLock(){
- WaitForSingleObject(mutex,waittime);
- --readerCount;
- if(readerCount==0)
- ReleaseSemaphore(db,1,NULL);
- ReleaseMutex(mutex);
- }
- void acquireWriteLock(){
- WaitForSingleObject(db,waittime);
- }
- void releaseWriteLock(){
- ReleaseSemaphore(db,1,NULL);
- }
- DWORD WINAPI readerFun(LPVOID lparam)
- {
- Sleep(readerSleep);
- acquireReadLock();
- cout<<"reader:"<<nr++<<endl;
- Sleep(readerSleep);
- releaseReadLock();
- return(0);
- }
- DWORD WINAPI writerFun(LPVOID lparam)
- {
- Sleep(writerSleep);
- acquireWriteLock();
- cout<<"writer:"<<nw++<<endl;
- Sleep(writerSleep);
- releaseWriteLock();
- return(0);
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- int i;
- HANDLE rThread[readerNum];
- HANDLE wThread[writerNum];
- mutex=CreateMutex(NULL,FALSE,NULL);
- db=CreateSemaphore(NULL,1,1,NULL);
- for(i=0 ; i<readerNum ;i++){
- rThread[i]=CreateThread(NULL,0,readerFun,&db,NULL,NULL);
- if(rThread[i]==NULL)
- return -1;
- }
- for(i=0 ; i<writerNum ; i++){
- wThread[i]=CreateThread(NULL,0,writerFun,&db,NULL,NULL);
- if(wThread[i]==NULL)
- return -1;
- }
- bool isContinue=true;
- while(isContinue){
- if(getchar())
- isContinue=false;
- }
- for(i=0 ;i<readerNum ; i++){
- CloseHandle(rThread[i]);
- }
- for(i=0 ; i<writerNum ; i++){
- CloseHandle(wThread[i]);
- }
- return 0;
- }
java初步实现:
阅读(2172) | 评论(0) | 转发(0) |