I have some code in a C++ CLR program with the below Critical Section code.
<pre lang="xml">
static CRITICAL_SECTION PrintCriticalSection;
void Test(int sleep1,int threadNumber)
{
cout<<"Thread "<<threadNumber<<" Starts. Sleeping for "<<sleep1<<" seconds.\n";
EnterCriticalSection(&PrintCriticalSection);
Sleep(sleep1);
LeaveCriticalSection(&PrintCriticalSection);
cout<<"Thread "<<threadNumber<<" Ends.\n";
}</pre>
I am calling this code using 2 Threads
<pre lang="xml">
class Program
{
Thread thread1;
Thread thread2;
PhoneCLR.PhonePortCLR test1;
PhoneCLR.PhonePortCLR test2;
static void Main(string[] args)
{
Program program1=new Program();
program1.Test1();
}
void Test1()
{
test1 = new PhonePortCLR(1, 1, 1, 1, true, false, true, false, 1);
test2 = new PhonePortCLR(1, 1, 1, 1, true, false, true, false, 1);
PhonePortCLR.InitGlobalOnce(1, false, false, false, false);
thread1 = new Thread(new ThreadStart(function1));
thread2 = new Thread(new ThreadStart(function2));
thread1.Start();
thread2.Start();
Console.ReadLine();
}
void function1()
{
test1.Test(10000, 1);
}
void function2()
{
test2.Test(100,2);
}
}
}
</pre>
The output in console window is supposed to be :
Thread 2 Starts. Sleeping for 100 seconds.
Thread 1 Starts. Sleeping for 10000 seconds.
///There is supposed to be a pause of 10,000 seconds here
Thread 2 Ends.
Thread 1 Ends.
But the output I am getting is random. Sometimes I get the above but sometimes I get below Output. It is so weird. Why is this the case? What can I use instead to fix this issue? Help!!!!! Its like 1 in 6 times I get below output. I am glad I caught this. I also notice that if I make the variable global instead of static, I get the below every time( Critical Section does not work)
The output in console window is sometimes:
Thread 2 Starts. Sleeping for 100 seconds.
Thread 1 Starts. Sleeping for 10000 seconds.
Thread 2 Ends.
///The 10 second pause happens now here...
Thread 1 Ends.