#include <iostream>
#include <windows.h>
using namespace std;
long g_lNum;
unsigned int _stdcall ThreadFun(void *pPM);
const int THREAD_NUM = 10;
CRITICAL_SECTION g_csThreadCode;
HANDLE hSemaphore;
int main()
{
g_lNum = 0;
HANDLE handle[10];
int i = 0;
InitializeCriticalSection(&g_csThreadCode);
hSemaphore = CreateSemaphore(NULL, 0, 1, NULL);
while(i < THREAD_NUM)
{
handle[i] = (HANDLE)_beginthreadex(NULL, 0, ThreadFun, &i, 0, NULL);
i++;
WaitForSingleObject(hSemaphore, INFINITE);
}
printf("end:%d\n", g_lNum);
WaitForMultipleObjects(THREAD_NUM, handle, TRUE, INFINITE);
DeleteCriticalSection(&g_csThreadCode);
CloseHandle(hSemaphore);
return 0;
}
unsigned int _stdcall ThreadFun(void *pPM)
{
int nThreadNum = *(int *)pPM;
//EnterCriticalSection(&g_csThreadCode);
Sleep(100);
g_lNum++;
Sleep(0);
printf("i:%d,g_lNum:%d\n", nThreadNum, g_lNum);
//LeaveCriticalSection(&g_csThreadCode);
ReleaseSemaphore(hSemaphore, 1, NULL);
//while(true);
return 0;
}
693

被折叠的 条评论
为什么被折叠?



