前段时间没事研究了一些生产者和消费者之间的问题,期间也查看了不少资料。又重新有了新的认识。特别作为一个IT农民工,必须要掌握的技能啊。

个人理解,这个应该说是一种模型吧,学会它,可以应用到多个方面的技术上去。数据流文件的读写,程序中的数据缓冲技术,播放缓冲技术等等。

废话不多说。。。直接上代码。下面是个C# 写的代码。比较粗糙,请谅解,有问题大家可以一起讨论研究。

 1 using System;
 2 using System.Threading;
 3 
 4 namespace Consumer
 5 {
 6     /// <summary>
 7     /// </summary>
 8     /// 用数组控制缓冲区,需要自己定义控制读取的位置
 9     public class BufferInArray
10     {
11         public const int BufferSize = 20;
12         public const int Max = 1000;
13         private int[] buffer = new int[BufferSize];
14 
15         private int bufferCount = 0;
16 
17         private int readLocation = 0, writeLocation = 0;
18 
19         public int GetBuffer()
20         {
21             lock (this)
22             {
23                 if (bufferCount == 0)
24                 {
25                     Monitor.Wait(this);
26                 }
27                 int readValue = buffer[readLocation];
28                 bufferCount--;
29                 readLocation = (readLocation + 1) % buffer.Length;
30                 Monitor.Pulse(this);
31                 return readValue;
32             }
33         }
34 
35         public void SetBuffer(int writeValue)
36         {
37             lock (this)
38             {
39                 if (bufferCount ==BufferSize)
40                 {
41                     Monitor.Wait(this);
42                 }
43                 buffer[writeLocation] = writeValue;
44                 bufferCount++;
45                 writeLocation = (writeLocation + 1) % buffer.Length;
46                 Monitor.Pulse(this);
47             }
48         }
49     }
50 
51     public class Producer
52     {
53         BufferInArray shared;
54 
55         public Producer(BufferInArray sharedLocation)
56         {
57             shared = sharedLocation;
58         }
59 
60         public void produce()
61         {
62             for (int count = 1; count <= BufferInArray.Max; count++)
63             {
64                 shared.SetBuffer(count);
65             }
66         }
67     }
68 
69     public class Consumer
70     {
71         private int value;
72         BufferInArray shared;
73 
74         public Consumer(BufferInArray sharedLocation)
75         {
76             shared = sharedLocation;
77         }
78 
79         public void consume()
80         {
81             for (int count = 1; count <= BufferInArray.Max; count++)
82             {
83                 value = shared.GetBuffer();
84             }
85         }
86     }
87 }

这个Demo是用的单缓冲数组技术。后续我还有双缓冲,环形缓冲等等。。。。

posted on 2014-09-11 01:29  homingfly  阅读(579)  评论(0编辑  收藏  举报