Skip to content

Instantly share code, notes, and snippets.

@kentkost
Created April 11, 2020 09:36
Show Gist options
  • Save kentkost/884b7a2a9684e84ae728fca20f4499e4 to your computer and use it in GitHub Desktop.
Save kentkost/884b7a2a9684e84ae728fca20f4499e4 to your computer and use it in GitHub Desktop.
Threads with semaphore and mutex and a variable #semaphore #threads #mutex
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace Threading
{
class Program
{
public static Semaphore semaphore = new Semaphore(2, 3);
public static int number = 1;
public static Mutex m = new Mutex();
static void Main(string[] args)
{
Thread t;
for (int i = 1; i <= 10; i++) {
ThreadStart ts = delegate
{
Console.WriteLine(Thread.CurrentThread.Name + " Wants to Enter into Critical Section for processing");
try {
semaphore.WaitOne();
bool moreWork = DoWork("param1", "param2", "param3");
if (moreWork) {
DoMoreWork("param1", "param2");
}
}
finally {
semaphore.Release();
}
};
t = new Thread(ts);
t.Name = "Thread " + i;
t.Start();
if (i == 10) {
t.Join(); //Or else main thread will continue and print the number
}
}
Console.WriteLine("number is: " + number);
Console.ReadKey();
}
static bool DoWork(string s1, string s2, string s3)
{
Thread.Sleep(1000);
m.WaitOne();
if (number == 4)
number--;
else {
number++;
}
m.ReleaseMutex();
Console.Write(Thread.CurrentThread.Name + " says: ");
Console.WriteLine(s1 + s2 + s3);
return true;
}
static void DoMoreWork(string s1, string s2)
{
Thread.Sleep(1000);
Console.Write(Thread.CurrentThread.Name + " says: ");
Console.WriteLine(s1 + s2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment