Hi
I trying to implement synchronization algorithm in C#, without success.
Why isn't the following code thread safe?
using System;
using System.Threading;
namespace SoftwareLockTest
{
class Program
{
private static volatile bool _isLocked1 = false;
private static volatile bool _isLocked2 = false;
private static volatile int _count = 0;
static void Main(string[] args)
{
Thread thread2 = new Thread(Thread2Work);
thread2.Start();
Thread1Work();
}
public static void Thread1Work()
{
while (true)
{
_isLocked1 = true;
while (_isLocked2)
{
_isLocked1 = false;
while (_isLocked2) ;
_isLocked1 = true;
}
CriticalSection();
_isLocked1 = false;
}
}
public static void Thread2Work()
{
while (true)
{
_isLocked2 = true;
while (_isLocked1)
{
_isLocked2 = false;
while (_isLocked1) ;
_isLocked2 = true;
}
CriticalSection();
_isLocked2 = false;
}
}
private static void CriticalSection()
{
if (_count != 0)
{
Console.WriteLine("NOT THREAD SAFE 1");
_count = 0;
}
_count++;
if (_count != 1)
{
Console.WriteLine("NOT THREAD SAFE 2");
}
_count--;
if (_count != 0)
{
Console.WriteLine("NOT THREAD SAFE 3");
}
}
}
}