zoukankan      html  css  js  c++  java
  • 生产者消费者模式及其存在的问题

     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,这样就会出现索引越界的问题。

    解决办法就是加锁。

  • 相关阅读:
    聪明的质检员 (二分)
    分巧克力(二分)
    产生冠军 HDU
    Legal or Not HDU
    确定比赛名次 HDU
    最短路径问题 HDU
    dijkstra算法为什么不能有负边?
    最短路 HDU
    dijkstra算法 模板
    Floyd算法模板--详解
  • 原文地址:https://www.cnblogs.com/wesley168/p/7837883.html
Copyright © 2011-2022 走看看