I am using inter-process synchronization on C#.NET Framework using named semaphore. Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace csharp_dot_net_frame
{
class Program
{
static void Main(string[] args)
{
try
{
Semaphore semaphoreObject = new Semaphore(initialCount: 1, maximumCount: 1, name: "my_sem");
Console.WriteLine("Waiting for semaphore");
semaphoreObject.WaitOne();
Console.WriteLine("Semaphore lock acquired");
Thread.Sleep(10000);
semaphoreObject.Release();
Console.WriteLine("exiting.");
Console.ReadLine();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
}
}
When I ran two instances(processes) say P1
and P2
of the above code, where P1
runs first then P2
and kill the P1
which has acquired the semaphore without releasing the hold semaphore, then the another process P2
which was waiting for semaphore on semaphoreObject.WaitOne();
deadlocks for infinite time. I want that P2
should definitely get the chance to wait the semaphoreObject
irrespective of whether P1
die or not.
The same problem was resolved on this post for UNIX C++ side using lockf
, wondering if some kind of similar alternative exists in C# as well. I am newbie on C# side, can someone please help me how to resolve this issue on C#.Net.
And also please suggest me the synchronization mechanism on Win32 C++ which is free from above condition of deadlock.
Thanks.