18.6. Granting Multiple Access to Resources with a Semaphore
Problem
You have a resource you want only a certain number of clients to access at a given time.
Solution
Use a semaphore to enable resource-counted access to the resource. For example, if you have an Xbox 360 and a copy of Halo3 (the resource) and a development staff eager to blow off some steam (the clients), you have to synchronize access to the Xbox 360. Since the Xbox 360 has four controllers, up to four clients can be playing at any given time. The rules of the house are that when you die, you give up your controller.
To accomplish this, create a class called Halo3Session
with a Semaphore
called _Xbox360
like this:
public class Halo3Session { // A semaphore that simulates a limited resource pool. private static Semaphore _Xbox360;
In order to get things rolling, you need to call the Play
method, as shown in Example 18-5, on the Halo3Session
class.
Example 18-5. Play method
public static void Play( ) { // An Xbox360 has 4 controller ports so 4 people can play at a time // We use 4 as the max and zero to start with, as we want Players // to queue up at first until the Xbox360 boots and loads the game // using (_Xbox360 = new Semaphore(0, 4, "Xbox360")) { using (ManualResetEvent GameOver = new ManualResetEvent(false)) { // // 9 Players log in to play // List<Xbox360Player.PlayerInfo> players = new List<Xbox360Player.PlayerInfo>( ) { new Xbox360Player.PlayerInfo { Name="Igor", Dead=GameOver}, new Xbox360Player.PlayerInfo { ...
Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.