Here's a quick Demo of a critical section...you dont have to use my class method.....but I like to......
Code:
#include <windows.h>
#include <process.h>
#include <stdio.h>
class CS_{
CRITICAL_SECTION cs;
public:
CS_(){InitializeCriticalSection(&cs);}
~CS_(){DeleteCriticalSection(&cs);}
void Enter(){EnterCriticalSection(&cs);}
void Leave(){LeaveCriticalSection(&cs);}
}CS;
void foo(void *no_op)
{
int i = 0;
for (i = 0; i < 50; i++)
{
CS.Enter();
printf("Thread 1: FOO\n");
CS.Leave();
}
}
void bar(void *no_op)
{
int i = 0;
for (i = 0; i < 50; i++)
{
CS.Enter();
printf("Thread 2: BAR\n");
CS.Leave();
}
}
int main(void)
{
UINT hHandles[2];
hHandles[0] = _beginthread(foo, 0, 0);
hHandles[1] = _beginthread(bar, 0, 0);
WaitForMultipleObjects(2,(CONST HANDLE*)(&hHandles),
TRUE,INFINITE);
return 0;
}
Also...removing the _endthread() from main would have stopped you app working....._endthread() was trying to stop your primary thread and whatever confusion that was causing was allowing the other threads to complete....without the _endthread() it was finishing the primary thread after the creation of the threads..therefore killing them before they could action......use one of the WaitFor##### APIs to stall the primary thread and allow the child threads to terminate naturally (as above)
<edit>Oh...and its unlikely you will see the direct benefit of a critical sec in my example...though its certianly safer and will avoid the problem adrian stated..its use is far more obvious if you are manipulation memory....like say a link list with multiple threads accessing data at the same time......imagine 1 thread reading a node as another is deleting it - bound to cause bugs! </edit>