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 117 118 119 120 121 122 123 124 125 126 127
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplicationPontAVoieUnique
{
class Program
{
public static int nbrA=0;
public static int nbrB = 0;
public static Semaphore semA;
public static Semaphore semB;
public static Semaphore semNbrA;
public static Semaphore semNbrB;
static void Main(string[] args)
{
semNbrA = new Semaphore(1, 2);
semNbrB = new Semaphore(1, 2);
semA = new Semaphore(2, 3);
semB = new Semaphore(2, 3);
Thread A1 = new Thread(new ThreadStart(ActionThreadA));
A1.IsBackground = true;
A1.Name = "A1";
A1.Start();
Thread B1 = new Thread(new ThreadStart(ActionThreadB));
B1.IsBackground = true;
B1.Name = "B1";
B1.Start();
Thread A2 = new Thread(new ThreadStart(ActionThreadA));
A2.IsBackground = true;
A2.Name = "A2";
A2.Start();
Thread B2 = new Thread(new ThreadStart(ActionThreadB));
B2.IsBackground = true;
B2.Name = "B2";
B2.Start();
Thread A3 = new Thread(new ThreadStart(ActionThreadA));
A3.IsBackground = true;
A3.Name = "A3";
A3.Start();
Thread B3 = new Thread(new ThreadStart(ActionThreadB));
B3.IsBackground = true;
B3.Name = "B3";
B3.Start();
Thread A4 = new Thread(new ThreadStart(ActionThreadA));
A4.IsBackground = true;
A4.Name = "A4";
A4.Start();
Thread B4 = new Thread(new ThreadStart(ActionThreadB));
B4.IsBackground = true;
B4.Name = "B4";
B4.Start();
Console.ReadLine();
}
static void ActionThreadA()
{
semNbrA.WaitOne();
nbrA++;
if (nbrA == 1)
{
Console.WriteLine(Thread.CurrentThread.Name + " I'am the first A ");
semB.WaitOne();
}
semNbrA.Release();
Console.WriteLine(Thread.CurrentThread.Name + " I'am in the cs ");
Thread.Sleep(5000); //sc
semNbrA.WaitOne();
nbrA--;
if (nbrA == 0)
{
Console.WriteLine(Thread.CurrentThread.Name + " I'am the last A ");
semB.Release();
}
semNbrA.Release();
}
static void ActionThreadB()
{
semNbrB.WaitOne();
nbrB++;
if (nbrB == 1)
{
Console.WriteLine(Thread.CurrentThread.Name + " I'am the first B ");
semA.WaitOne();
}
semNbrB.Release();
Console.WriteLine(Thread.CurrentThread.Name + " I'am in the cs ");
Thread.Sleep(5000);
semNbrB.WaitOne();
nbrB--;
if (nbrB == 0)
{
Console.WriteLine(Thread.CurrentThread.Name + " I'am the last B ");
semA.Release();
}
semNbrB.Release();
}
}
} |
Partager