i have a simple C program that uses CRITICAL_SECTION.
for some reason it seem to enter the CRITICAL_SECTION again and again and not really execute the code inside, causing the threads to deadlocked.
i cannot seem to find the reason for this.
here is the code:
#include <windows.h>
#include <iostream>
#define N 100000000
CRITICAL_SECTION cs;
static DWORD WINAPI safe_increment(void *param)
{
volatile long* x = (volatile long*)param;
for(int i=0;i<N;++i)
EnterCriticalSection(&cs);
++(*x);
LeaveCriticalSection(&cs);
return 0;
}
void main()
{
InitializeCriticalSection(&cs);
volatile long x = 0;
HANDLE h[2];
DWORD thread_id;
int x = 0;
h[0] = CreateThread(NULL,0,safe_increment,(void*)&x,0,&thread_id);
h[1] = CreateThread(NULL,0,safe_increment,(void*)&x,0,&thread_id);
WaitForMultipleObjects(2,h,TRUE,INFINITE);
CloseHandle(h[0]);
CloseHandle(h[1]);
DeleteCriticalSection(&cs);
std::cout << "Result of safe increment: " << x << "\n";
}
thank you!
Roy.
Mistake in
forloop. Should be:No braces so the
forloop only executedEnterCriticalSection()and nothing else. The first thread that acquired the critical section never released it: deadlock.