// Critical.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
#include <iostream>
using namespace std;
static int nGloble = 0;
CRITICAL_SECTION gcs;
DWORD WINAPI RecvThread(LPVOID lp)
{
int num = *(DWORD*)lp;
while (nGloble < 1000)
{
printf("Thread %d nGloble = %d\n", num, nGloble);
EnterCriticalSection(&gcs);
nGloble++;
LeaveCriticalSection(&gcs);
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
InitializeCriticalSection(&gcs);
HANDLE Thread[10];
for(int i=0; i<10; i++)
{
Thread[i] = CreateThread(NULL, 0, RecvThread, &i, 0, NULL);
Sleep(500);
}
WaitForMultipleObjects(10, Thread, TRUE, 100000);
DeleteCriticalSection(&gcs);
CloseHandle(Thread);
return 0;
}
一个简单的多线程例子-临界区
最新推荐文章于 2022-04-28 11:25:54 发布