-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPingPongResetEvent.cs
More file actions
85 lines (66 loc) · 2.16 KB
/
PingPongResetEvent.cs
File metadata and controls
85 lines (66 loc) · 2.16 KB
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
using System;
using System.Threading;
namespace PingPongResetEvent
{
public class Match
{
public int Rounds { get; set; }
public Player Player1 { get; private set; }
public Player Player2 { get; private set; }
public Match(Player player1, Player player2, int rounds)
{
this.Player1 = player1;
this.Player2 = player2;
this.Rounds = rounds;
}
public void Begin()
{
var player1Thread = new Thread(new ThreadStart(() => { Player1.SetupMatch(this, Player2); }));
var player2Thread = new Thread(new ThreadStart(() => { Player2.SetupMatch(this, Player1); }));
player1Thread.Start();
player2Thread.Start();
var completeActions = new ManualResetEvent[] { Player1.GameComplete, Player2.GameComplete };
Player1.Start();
WaitHandle.WaitAll(completeActions);
}
}
public class Player
{
private string _message;
public AutoResetEvent MoveComplete { get; private set; }
public ManualResetEvent GameComplete { get; private set; }
public Player(string message)
{
this._message = message;
this.MoveComplete = new AutoResetEvent(false);
this.GameComplete = new ManualResetEvent(false);
}
public void Start()
{
MoveComplete.Set();
}
public void SetupMatch(Match match, Player opponent)
{
while (match.Rounds > 1)
{
opponent.MoveComplete.WaitOne();
Console.WriteLine(_message + "(" + match.Rounds.ToString() + ")");
match.Rounds--;
MoveComplete.Set();
}
GameComplete.Set();
}
}
class Program
{
static void Main(string[] args)
{
var player1 = new Player("Pong!");
var player2 = new Player("Ping!");
var match = new Match(player1, player2, 3);
Console.WriteLine("Ready...Set...Go!");
match.Begin();
Console.WriteLine("Done!");
}
}
}