Hi, you shoud initialize your critical section only once in your main thread. And also you have to free resources it holds by calling DeleteCriticalSection(...);
#include"Derived.h"
CRITICAL_SECTION VarCS;
int main()
{
InitializeCriticalSection(&VarCS);
for(int i=0;i<=2;i++)
{
Derived *pDerived=new Derived();
pDerived->fun();
Sleep(30000);
}
DeleteCriticalSection(&VarCS);
return 0;
}
Also try to consider TryEnterCriticalSection call instead of EnterCriticalSection, which is blocking your thread.
The critical section is the best choice if you plan to create single process solution. Mutexes and semaphores not as fast as critical section. Please see Jeffrey Richter's "Windows via C/C++", or please refer to MSDN (
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682530(v=vs.85).aspx[
^])