I'm having problems getting the Win32 CriticalSection calls to work. In the following code, the call to EnterCriticalSection seems to be ignored, and each call to SearchFunc gets the value 'z', rather than the first getting 'A', the second getting 'a', and the third getting 'z'.
Am I doing something wrong, or leaving something out?
I was expecting that the matched pairs of EnterCriticalSection and LeaveCriticalSection would prevent the main thread from running past the _beginthreadex calls until each thread had a chance to get started. The threads should run for 5 seconds, with interspersed A's and a's and z's. Instead, all three threads seem to be created as if called with 'z'. Also, I'm not certain that three threads are created.
// EeTestMultiThread.cpp
#include "stdafx.h"
#include <process.h>
CRITICAL_SECTION gCriticalSection;
volatile DWORD gTickCountStop;
#define PROXY_LIMIT 50000000
UINT __stdcall SearchFunc(void* pArguments)
{
UINT* pArgs = (UINT*)pArguments;
UINT curTransIndex = *pArgs;
UINT proxyFoundCount = 0;
::printf("Reached SearchFunc: %d\n", curTransIndex);
::LeaveCriticalSection(&gC
riticalSec
tion);
while (TRUE) {
UINT curTickCount = ::GetTickCount();
if (curTickCount > gTickCountStop) {
break;
}
proxyFoundCount += curTransIndex;
if (proxyFoundCount > PROXY_LIMIT) {
printf("%c", curTransIndex);
proxyFoundCount = 0;
}
}
printf("Search: %d\n", proxyFoundCount);
::_endthreadex(0);
return 0;
}
int main(void)
{
::InitializeCriticalSectio
n(&gCritic
alSection)
;
gTickCountStop = (::GetTickCount() + 5000); // Run for 5 seconds
UINT threadID;
HANDLE hThread[3];
UINT transIndex = 'A';
::EnterCriticalSection(&gC
riticalSec
tion);
hThread[0] = (HANDLE)::_beginthreadex(N
ULL, 0, &SearchFunc,
&transIndex, 0, &threadID);
transIndex = 'a';
::EnterCriticalSection(&gC
riticalSec
tion);
hThread[1] = (HANDLE)::_beginthreadex(N
ULL, 0, &SearchFunc,
&transIndex, 0, &threadID);
transIndex = 'z';
::EnterCriticalSection(&gC
riticalSec
tion);
hThread[2] = (HANDLE)::_beginthreadex(N
ULL, 0, &SearchFunc,
&transIndex, 0, &threadID);
::WaitForMultipleObjects(3
, hThread, TRUE, INFINITE);
::DeleteCriticalSection(&g
CriticalSe
ction);
return 0;
}
Start Free Trial