Created
April 11, 2020 09:07
-
-
Save kentkost/dc44bbcc6e2cba6b7035277c979357d4 to your computer and use it in GitHub Desktop.
Threads with semaphore #semaphore #thread
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
namespace MutexDemo | |
{ | |
class Program | |
{ | |
public static Semaphore semaphore = new Semaphore(2, 3); | |
static void Main(string[] args) | |
{ | |
for (int i = 1; i <= 10; i++) | |
{ | |
Thread threadObject = new Thread(DoSomeTask) | |
{ | |
Name = "Thread " + i | |
}; | |
threadObject.Start(i); | |
} | |
Console.ReadKey(); | |
} | |
static void DoSomeTask(object id) | |
{ | |
Console.WriteLine(Thread.CurrentThread.Name + " Wants to Enter into Critical Section for processing"); | |
try | |
{ | |
//Blocks the current thread until the current WaitHandle receives a signal. | |
semaphore.WaitOne(); | |
Console.WriteLine("Success: " + Thread.CurrentThread.Name + " is Doing its work"); | |
Thread.Sleep(5000); | |
Console.WriteLine(Thread.CurrentThread.Name + "Exit."); | |
} | |
finally | |
{ | |
//Release() method to releage semaphore | |
semaphore.Release(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment