Skip to content

Instantly share code, notes, and snippets.

@kentkost
Created April 11, 2020 09:07
Show Gist options
  • Save kentkost/dc44bbcc6e2cba6b7035277c979357d4 to your computer and use it in GitHub Desktop.
Save kentkost/dc44bbcc6e2cba6b7035277c979357d4 to your computer and use it in GitHub Desktop.
Threads with semaphore #semaphore #thread
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