#include <iostream>
#include <process.h>
#include <windows.h>
long g_count = 0;
long g_sum = 0;
static const int g_s_Count = 10;
CRITICAL_SECTION g_csThreadParamer;
CRITICAL_SECTION g_csThreadCode;
HANDLE g_threadEvent;
unsigned int WINAPI ThreadFunc(void *p) {
int nThreadNum = *(int *)p;
Sleep(50);
EnterCriticalSection(&g_csThreadCode);
g_count++;
printf("线程编号: %d, 全局资源值为: %d\n", nThreadNum, g_count);
LeaveCriticalSection(&g_csThreadCode);
SetEvent(g_threadEvent);
return 0;
}
int main(void) {
std::cout << "Create the Thread" << std::endl;
g_threadEvent = CreateEvent( NULL,
FALSE,
FALSE,
NULL);
InitializeCriticalSection(&g_csThreadCode);
InitializeCriticalSection(&g_csThreadParamer);
HANDLE threadHandle[g_s_Count];
for(int i = 0; i < g_s_Count; ) {
threadHandle[i] = (HANDLE)_beginthreadex(NULL,
0,
ThreadFunc,
&i,
0,
NULL);
++i;
}
WaitForMultipleObjects(g_s_Count, threadHandle, true, INFINITE);
for(int i = 0; i < g_s_Count; ++i) {
CloseHandle(threadHandle[i]);
}
DeleteCriticalSection(&g_csThreadCode);
DeleteCriticalSection(&g_csThreadParamer);
std::cout << "Thread Ending" << std::endl;
return 0;
}
分4步:
1,初始化CS段。
2,EnterCS段。
3,离开CS段。//主线程调度其他等待的线程执行。很好的达到互斥,但是不能同步。
4.,删除CS段。