1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication7
{
class Program
{
private static object _panierPasPlein = new object();
private static object _panierPasVide = new object();
private static object _mutex = new object();
Random rnd = new Random();
private static int panier1 = 0;
static void Main(string[] args)
{
Console.Title = "Exemple de Mutex";
Thread fab = new Thread(Fabric);
fab.Start();
Thread conso = new Thread(Conso);
conso.Start();
Console.ReadKey();
}
private static void Fabric()
{
while (true)
{
int nombreElements;
lock (_mutex)
{
nombreElements = panier1;
}
//sleep
while (nombreElements == 5)
{
Console.WriteLine(" Le panier 1 est complet");
lock (_panierPasPlein)
{
Monitor.Wait(_panierPasPlein);
}
lock (_mutex)
{
nombreElements = panier1;
}
}
lock(_mutex)
{
Console.WriteLine(" Fabrication d'une piece P1 -- ({0})", panier1);
panier1++;
}
lock (_panierPasVide)
{
Monitor.Pulse(_panierPasVide);
}
}
}
private static void Conso()
{
while (true)
{
int nombreElements;
//sleep
lock (_panierPasVide)
{
Monitor.Wait(_panierPasVide);
}
lock(_mutex)
{
nombreElements = panier1;
}
while (nombreElements == 0)
{
Console.WriteLine(" Le panier 1 est vide");
lock (_panierPasVide)
{
Monitor.Wait(_panierPasVide);
lock (_mutex)
{
nombreElements = panier1;
}
}
}
lock(_mutex)
{
panier1--;
Console.WriteLine("Consommation d'une piece P1 -- ({0})", panier1);
}
lock (_panierPasPlein)
{
Monitor.Pulse(_panierPasPlein);
}
}
}
}
} |
Partager