I was learning about volatile , interlock and lock in C#, Wrote below code to print odd and even numbers without using any of these synchronization construct, I ran this code several times and always gives proper answer,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace microsoft
{
class th2_odd_event
{
static int num = 1;
static bool guard = false;
public void init()
{
Thread th = new Thread(print_odd);
Thread th2 = new Thread(print_even);
th.Start();
th2.Start();
}
public static void print_odd()
{
while (true)
{
if (guard == false)
{
if (num % 2 != 0)
{
Console.WriteLine(num);
num++;
}
guard = true;
}
if (num > 20)
break;
}
}
public static void print_even()
{
while (true)
{
if (guard == true)
{
if (num % 2 == 0)
{
Console.WriteLine(num);
num++;
}
guard = false;
}
if (num > 20)
break;
}
}
}
How this code working ? Is it by luck , there is no clash between two thread ? I missing something...