生产者消费者模式及其存在的问题

 1  class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             //池子
 6             MyConnction[]  connections = new MyConnction[100];
 7 
 8             //创建一个消费者
 9             int index = -1;
10             for (int i = 0; i < 10; i++)
11             {
12                 Thread thread = new Thread(()=> {
13                     while (true)
14                     {
15                         lock (connections)
16                         {
17                             if (index >= 0)//池子中有数据
18                             {
19                                 connections[index] = null;
20                                 Console.WriteLine("消费者消费了一个产品!" + index);
21                                 index--;//消费掉一个产品后,指针移到上一个产品的位置
22                             } 
23                         }
24                         
25 
26                         Thread.Sleep(700);
27                     }
28                 });
29 
30                 thread.IsBackground = true;
31                 thread.Start();
32             }
33 
34             //创建5个生产者
35             for (int i = 0; i < 5; i++)
36             {
37                 Thread thread = new Thread(() => {
38                     while (true)
39                     {
40                         lock (connections)
41                         {
42                             if (index < connections.Length)//池子中有数据
43                             {
44                                 connections[index + 1] = new MyConnction();
45                                 Console.WriteLine("生产者生产了一个产品!" + (index + 1));
46                                 index++;//消费掉一个产品后,指针移到上一个产品的位置
47                             }
48 
49                         }
50 
51                         Thread.Sleep(500);
52                     }
53                 });
54 
55                 thread.IsBackground = true;
56                 thread.Start();
57             }
58 
59 
60             Console.ReadKey();
61         }
62     }
63 
64     public class MyConnction{}
View Code

如果开始没有加锁,可能会导致以下问题:

 

 原因是多个线程请求同一个资源的时候,假如开始index=2,满足if中的条件的消费者有4个,那么就会消耗四次,事实上,只能消费3次。所以最终index=-1,这样就会出现索引越界的问题。

解决办法就是加锁。

转载于:https://www.cnblogs.com/wesley168/p/7837883.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值