1: UsingSystem;
2: UsingSystem. Collections. Generic;
3: UsingSystem. LINQ;
4: UsingSystem. text;
5: UsingSystem. Threading;
6: UsingSystem. diagnostics;
7:
8: NamespaceSemaphore
9:{
10:ClassProgram
11:{
12:Static VoidMain (String[] ARGs)
13:{
14:IntThreadcount = 6;
15:IntSemaphorecount = 4;
16:VaR semaphore =NewSemaphoreslim (semaphorecount, semaphorecount );
17:VaR threads =NewThread [threadcount];
18:
19:For(IntI = 0; I <threadcount; I ++)
20:{
21:Threads [I] =NewThread (threadmain );
22:Threads [I]. Start (semaphore );
23:}
24:
25:For(IntI = 0; I <threadcount; I ++)
26:{
27:Threads [I]. Join ();
28:}
29:
30:Console. writeline ("All threads finished");
31:}
32:
33:Static VoidThreadmain (ObjectO)
34:{
35:Semaphoreslim semaphore = oAsSemaphoreslim;
36:Trace. Assert (semaphore! =Null,"O must be a semaphore type");
37:BoolIscompleted =False;
38:While(! Iscompleted)
39:{
40:If(Semaphore. Wait (600 ))
41:{
42:Try
43:{
44:Console. writeline ("Thread {0} locks the semaphore", Thread. currentthread. managedthreadid );
45:Thread. Sleep (2000 );
46:}
47:Finally
48:{
49:Semaphore. Release ();
50:Console. writeline ("Thread {0} releases the semaphore", Thread. currentthread. managedthreadid );
51:Iscompleted =True;
52:}
53:}
54:Else
55:{
56:Console. writeline ("Timeout for thread {0}: Wait again", Thread. currentthread. managedthreadid );
57:}
58:}
59:Console. Read ();
60:}
61:}
62:}