基于C#實(shí)現(xiàn)的多生產(chǎn)者多消費(fèi)者同步問(wèn)題實(shí)例
更新時(shí)間:2014年09月10日 12:00:41 投稿:shichen2014
這篇文章主要介紹了基于C#實(shí)現(xiàn)的多生產(chǎn)者多消費(fèi)者同步問(wèn)題,包括了加鎖與釋放鎖,以及對(duì)應(yīng)臨界資源的訪問(wèn)。是比較實(shí)用的技巧,需要的朋友可以參考下
本文實(shí)例講述了基于C#實(shí)現(xiàn)的多生產(chǎn)者多消費(fèi)者同步問(wèn)題,分享給大家供大家參考之用。具體代碼如下:
// 多個(gè)生產(chǎn)者和多個(gè)消費(fèi)者,能生產(chǎn)n個(gè)產(chǎn)品的情況
using System;
using System.Threading;
public class HoldIntegerSynchronized{
private int[] buffer; //緩沖區(qū)
private int occupiedBufferCount = 0;
private int readPosition = 0 , writePosition = 0;
//下一個(gè)讀到的位置和寫到的位置
public HoldIntegerSynchronized(int capacity){
buffer = new int[capacity];
}
public int BufferSize{
get{
return buffer.Length;
}
}
public int Buffer{
get{
int bufferCopy;
// 加鎖
lock(this){
while(occupiedBufferCount == 0){ //多個(gè)消費(fèi)者,所以此處改用while
Console.WriteLine(Thread.CurrentThread.Name + " tries to read. ");
DisplayState("Buffer Empty. " + Thread.CurrentThread.Name + " waits.");
Monitor.Wait(this);
// 為臨界區(qū)之外等待的生產(chǎn)者放行,讓他來(lái)"生產(chǎn)"
// 一直到生產(chǎn)者生產(chǎn)結(jié)束,調(diào)用了Monitor.PauseAll()
// 才能繼續(xù)執(zhí)行下去,此時(shí),消費(fèi)者自動(dòng)重新獲得this的鎖
}
--occupiedBufferCount;
bufferCopy = buffer[readPosition];
readPosition = (readPosition + 1) % buffer.Length;
DisplayState(Thread.CurrentThread.Name + " reads " + bufferCopy);
// 通知,讓等待的 生產(chǎn)者線程 進(jìn)入Started狀態(tài),如果生產(chǎn)者處于臨界區(qū)之外,這句話執(zhí)行完后他仍然在臨界區(qū)之外
Monitor.PulseAll(this);
// 釋放鎖
}//lock
return bufferCopy;
}
set{
// 加鎖
lock(this){
while(occupiedBufferCount == buffer.Length){
Console.WriteLine(Thread.CurrentThread.Name + " tries to write. ");
DisplayState("Buffer Full. " + Thread.CurrentThread.Name + " waits.");
Monitor.Wait(this);
// 為臨界區(qū)之外等待消費(fèi)者放行,讓他來(lái)"消費(fèi)"
// 一直到消費(fèi)者調(diào)用了Monitor.Pause()
// 才能繼續(xù)執(zhí)行下去,此時(shí),生產(chǎn)者自動(dòng)重新獲得this的鎖
}
buffer[writePosition] = value;
++occupiedBufferCount;
writePosition = (writePosition + 1) % buffer.Length;
DisplayState(Thread.CurrentThread.Name + " writes " + value);
// 通知,讓W(xué)ait狀態(tài)的 消費(fèi)者 進(jìn)入Started狀態(tài),如果消費(fèi)者處于臨界區(qū)之外,這句話執(zhí)行完后他仍然在臨界區(qū)之外
Monitor.PulseAll(this);
// 釋放鎖
}
}
}
public void DisplayState(string operation){
Console.Write("{0,-35}",operation);
for(int i = 0; i < BufferSize; i++ ){
int a = readPosition;
int b = writePosition;
if( a <= i && i < b) {
Console.Write("{0,-9}",buffer[i]);
}else if( b < a && !( b <= i && i < a ) ){
Console.Write("{0,-9}",buffer[i]);
}else if( occupiedBufferCount == BufferSize){
Console.Write("{0,-9}",buffer[i]);
}else{
Console.Write("{0,-9}","");
}
}
Console.WriteLine("{0}/r/n",occupiedBufferCount);
}
}
class Producer{
private HoldIntegerSynchronized sharedLocation;
private Random randomSleepTime;
public Producer(HoldIntegerSynchronized shared,Random random){
sharedLocation = shared;
randomSleepTime = random;
}
public void Produce(){
for (int count=0; count<3; count++) {
Thread.Sleep(randomSleepTime.Next(1,2000));
sharedLocation.Buffer = randomSleepTime.Next(5,10);
}
Console.WriteLine(Thread.CurrentThread.Name + " done producing./r/nTerminating " + Thread.CurrentThread.Name + "./r/n");
}
}
class Consumer{
private HoldIntegerSynchronized sharedLocation;
private Random randomSleepTime;
public Consumer(HoldIntegerSynchronized shared,Random random){
sharedLocation = shared;
randomSleepTime = random;
}
public void Consume(){
int sum = 0;
for (int count=0; count<4; count++) {
Thread.Sleep(randomSleepTime.Next(1,2000));
sum += sharedLocation.Buffer;
}
Console.WriteLine(Thread.CurrentThread.Name + " read values totaling:" + sum + "/r/nTerminating " + Thread.CurrentThread.Name + ".");
}
}
class SharedCell{
static void Main(string[] args){
HoldIntegerSynchronized holdInteger = new HoldIntegerSynchronized(5);
Random random = new Random();
Thread[] producerThreads = new Thread[4];
Thread[] consumerThreads = new Thread[3];
Console.Write("{0,-35}","Operation");
for(int i = 0;i < holdInteger.BufferSize;i++){
Console.Write("{0,-9}","Elem " + i);
}
Console.WriteLine("Occupied Count/r/n");
for(int i = 0; i < producerThreads.Length;i++){
Producer producer = new Producer(holdInteger,random);
producerThreads[i] = new Thread(new ThreadStart(producer.Produce));
producerThreads[i].Name = "Producer No." + i;
}
for(int i = 0; i < consumerThreads.Length;i++){
Consumer consumer = new Consumer(holdInteger,random);
consumerThreads[i] = new Thread(new ThreadStart(consumer.Consume));
consumerThreads[i].Name = "Consumer No." + i;
}
for(int i = 0; i < producerThreads.Length;i++){
producerThreads[i].Start();
}
for(int i = 0; i < consumerThreads.Length;i++){
consumerThreads[i].Start();
}
}
}
希望本文所述對(duì)大家C#程序設(shè)計(jì)的學(xué)習(xí)有所幫助。
您可能感興趣的文章:
- C# 委托的三種調(diào)用示例(同步調(diào)用 異步調(diào)用 異步回調(diào))
- c#(Socket)同步套接字代碼示例
- C#應(yīng)用BindingSource實(shí)現(xiàn)數(shù)據(jù)同步的方法
- c#.net多線程編程教學(xué)——線程同步
- C#同步、異步遠(yuǎn)程下載文件實(shí)例
- c#實(shí)現(xiàn)數(shù)據(jù)同步的方法(使用文件監(jiān)控對(duì)象filesystemwatcher)
- C#同步網(wǎng)絡(luò)時(shí)間的方法實(shí)例詳解
- c#線程同步使用詳解示例
- 解析C#中委托的同步調(diào)用與異步調(diào)用(實(shí)例詳解)
- C#使用AutoResetEvent實(shí)現(xiàn)同步
相關(guān)文章
基于不要返回null之EmptyFactory的應(yīng)用詳解
本篇文章對(duì)不要返回null之EmptyFactory進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
C#中構(gòu)造函數(shù)和析構(gòu)函數(shù)用法實(shí)例詳解
這篇文章主要介紹了C#中構(gòu)造函數(shù)和析構(gòu)函數(shù)用法,結(jié)合實(shí)例形式詳細(xì)分析了C#中構(gòu)造函數(shù)與析構(gòu)函數(shù)的原理、定義、使用方法與相關(guān)注意事項(xiàng),需要的朋友可以參考下2016-06-06
C#獲取兩個(gè)數(shù)的最大公約數(shù)和最小公倍數(shù)示例
本文介紹了使用C#獲取兩個(gè)數(shù)的最大公約數(shù)和最小公倍數(shù)的示例,大家參考使用吧2014-01-01
詳解C#中三個(gè)關(guān)鍵字params,Ref,out
本文主要討論params關(guān)鍵字,ref關(guān)鍵字,out關(guān)鍵字。非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下吧2017-05-05
Visual C#類的定義及實(shí)現(xiàn)方法實(shí)例解析
這篇文章主要介紹了Visual C#類的定義及實(shí)現(xiàn)方法實(shí)例解析,對(duì)于新手來(lái)說(shuō)有不錯(cuò)的借鑒學(xué)習(xí)價(jià)值,需要的朋友可以參考下2014-07-07

