Re: EnterCriticalSection
Oh, sorry. Discard my previous answer, I misread your post.
"Sam" wrote:
I have 2 threads in my program which should not enter a critical
section at the same time. To achieve this, I use the following
program fragment:
CRITICAL_SECTION cs;
//main thread
BOOL res= InitializeCriticalSectionAndSpinCount(&cs,0);
assert(res);
...
DeleteCriticalSection(&cs);
The question is why do you delete the critical section object
right after it is created? Also, you need to ensure that both main
thread and worker thread use the same critical section object.
Basically, the flow is like this:
CRITICAL_SECTION g_cs;
// ---- main thread ----
InitializeCriticalSection(&g_cs);
....
EnterCriticalSection(&g_cs);
// access shared resource
// ...
LeaveCriticalSection(&g_cs);
....
// wait for worker thread to finish
WaitForSingleObject(hWorkerThread, ...);
// release CS
DeleteCriticalSection(&g_cs);
// ---- worker thread ----
EnterCriticalSection(&g_cs);
// access shared resource
// ...
LeaveCriticalSection(&g_cs);
The call to `EnterCriticalSection' will block the execution of
calling thread until some other thread owns CS object.
HTH
Alex