当我尝试学习多线程时,我从谷歌搜索中获得了以下代码。我在使用 CRITICAL SECTION 和没有 CRITICAL SECTION 的情况下运行代码,但是在执行这两种情况之后,我不明白为什么这段代码的作者使用 CRITICAL SECTION。
static unsigned int counter = 100;
static bool alive = true;
CRITICAL_SECTION cs;
static unsigned __stdcall Sub(void *args)
{
while(alive)
{
EnterCriticalSection(&cs);
cout << "[Sub(" << counter << ")]---" << endl;
counter -= 10;
LeaveCriticalSection(&cs);
Sleep(500);
}
return 0;
}
static unsigned __stdcall Add(void *args)
{
while(alive)
{
EnterCriticalSection(&cs);
cout << "[Add(" << counter << ")]+++" << endl;
counter += 10;
LeaveCriticalSection(&cs);
Sleep(500);
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
InitializeCriticalSection(&cs);
unsigned add;
HANDLE hAdd = (HANDLE)_beginthreadex(0,0,&Add,0,CREATE_SUSPENDED, &add);
assert(hAdd != 0);
unsigned sub;
HANDLE hSub = (HANDLE)_beginthreadex(0,0,&Sub,0,CREATE_SUSPENDED, &sub);
assert(hSub != 0);
//start threads
ResumeThread(hAdd);
ResumeThread(hSub);
//let threads run for 10 seconds
Sleep(3000);
alive = false;
WaitForSingleObject(hSub, INFINITE);
CloseHandle(hSub);
WaitForSingleObject(hAdd, INFINITE);
CloseHandle(hAdd);
return 0;
}