多线程读写进程
注意這里為什么不用mutex,因為只能是對mutex加鎖的線程對其解鎖,其他線程不能解鎖
http://blog.csdn.net/caotiancool/article/details/374101
讀者優先算法:
設置兩個互斥信號量:rwmutex?用于寫者與其他讀者/寫者互斥的訪問共享數據
??????????????????? rmutex??用于讀者互斥的訪問讀者計數器readcount
var rwmutex, rmutex : semaphore := 1,1 ;
int readcount = 0;?
cobegin
? ? ? ?readeri begin ?// i=1,2,….
? ? ? ? ? ? ? P(rmutex);
? ? ? ? ? ? ? Readcount++;
? ? ? ? ? ? ? If (readcount == 1) P(rwmutex);//當有第一個讀者進入時,就對寫信號加鎖;則后續讀者,直接讀,不須判斷是否有寫進程
? ? ? ? ? ? ? V(rmutex);
? ? ? ? ? ? ? 讀數據;
? ? ? ? ? ? ? P(rmutex);
? ? ? ? ? ? ? Readcount--;
? ? ? ? ? ? ? If (readcount == 0) V(rwmutex);//當最后一個讀者離開時,對寫信號解鎖
? ? ? ? ? ? ? V(rmutex);
? ? ? ?End
? ? ? ?Writerj begin // j = 1,2,….
? ? ? ? ? ? ? P(rwmutex);//只有當最后一個讀者離開后,才能寫
? ? ? ? ? ? ? 寫更新;
? ? ? ? ? ? ? V(rwmutex);
? ? ? ?End?
Coend?
寫者優先:
條件:
1)多個讀者可以同時進行讀
2)寫者必須互斥(只允許一個寫者寫,也不能讀者寫者同時進行)
3)寫者優先于讀者(一旦有寫者,則后續讀者必須等待,喚醒時優先考慮寫者)
解1:如果讀者數是固定的,我們可采用下面的算法:
rwmutex:用于寫者與其他讀者/寫者互斥的訪問共享數據?
rmutex:?該信號量初始值設為10,表示最多允許10個讀者進程同時進行讀操作
var rwmutex, rmutex?:?semaphore := 1,10?;
cobegin
?????? readeri begin? // i=1,2,….
?????? ?????? P(rwmutex);? //讀者、寫者互斥
?????? ?????? P(rmutex);
?????? ?????? V(rwmutex); ?//?釋放讀寫互斥信號量,允許其它讀、寫進程訪問資源
?????? ???????讀數據;
?????? ?????? V(rmutex);
?????? End?????? ??????
?????? Writerj begin // j = 1,2,….
?????? ?????? P(rwmutex);
?????? ?????? For (i=1;i<=10;i++) P(rmutex); //禁止新讀者,并等待已進入的讀者退出
?????? ???????寫更新;
?????? ?????? For (i=1;i<=10;i++) V(rmutex); //?恢復允許rmutex?值為10
?????? ?????? V(rwmutex);?
?????? End?
Coend
?
解2:如果讀者數不固定,采用下面的算法:
設置三個互斥信號量:rwmutex?用于寫者與其他讀者/寫者互斥的訪問共享數據
????? ?????? ?????? rmutex??用于讀者互斥的訪問讀者計數器readcount?????? ?????? ?????? ????????? ????????????????? ? nrmutex?用于寫者等待已進入讀者退出,所有讀者退出前互斥寫操作
var rwmutex, rmutex,nrmutex?:?semaphore := 1,1,1?;?
int readcount = 0;
cobegin
?????? readeri begin? // i=1,2,….
?????? ?????? P(rwmutex); // 寫進程優先,一旦有寫的進程,就不再允許有讀的進程再加入了
?????? ?????? P(rmutex);
?????? ?????? Readcount++;
?????? ?????? If (readcount == 1) P(nrmutex); //有讀者進入,互斥寫操作//nrmutex用來判斷是否還有讀者
?????? ?????? V(rmutex);
?????? ?????? V(rwmutex); //?及時釋放讀寫互斥信號量,允許其它讀、寫進程申請資源
?????? ???????讀數據;
?????? ?????? P(rmutex);
?????? ?????? Readcount--;
?????? ?????? If (readcount == 0) V(nrmutex); //所有讀者退出,允許寫更新
?????? ?????? V(rmutex);
?????? End
?????? Writerj begin // j = 1,2,….
?????? ?????? P(rwmutex);? //?互斥后續其它讀者、寫者
?????? ?????? P(nrmutex); ?//如有讀者正在讀,等待所有讀者讀完
?????? ???????寫更新;
?????? ?????? V(nrmutex); ??//允許后續新的第一個讀者進入后互斥寫操作?
?????? ?????? V(rwmutex);? //允許后續新讀者及其它寫者
?????? End?
Coend
總結
- 上一篇: 多线程生产者和消费者
- 下一篇: young氏矩阵