1.SingalObject
#include <windows.h>
#include <iostream>
using namespace std;
CRITICAL_SECTION cs;
int m = 0;
int n = 0;
DWORD WINAPI ThreadProc(LPVOID Param);
int main()
{
InitializeCriticalSection(&cs);
int a = 10;
HANDLE ThreadHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadProc,NULL, 0, NULL);
EnterCriticalSection(&cs);
for (int i = 0;i<1000;i++)
{
m++;
n++;
printf("Main Thread\r\n");
}
LeaveCriticalSection(&cs);
WaitForSingleObject(ThreadHandle, INFINITE);
1.SingalObeject
DeleteCriticalSection(&cs);
printf("%d %d\r\n", m, n);
}
DWORD WINAPI ThreadProc(LPVOID Param)
{
EnterCriticalSection(&cs);
for (int i = 0; i < 1000; i++)
{
printf("Sub Thread\r\n");
m++;
n++;
}
LeaveCriticalSection(&cs);
return 0;
}
2.MultipleObject
#include <windows.h>
#include <iostream>
using namespace std;
CRITICAL_SECTION cs;
int m = 0;
int n = 0;
DWORD WINAPI ThreadProc(LPVOID Param);
int main()
{
HANDLE ThreadHandle[5] = { 0 };
InitializeCriticalSection(&cs);
for (int i = 0; i < 5; i++)
{
ThreadHandle[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadProc, NULL, 0, NULL);
}
WaitForMultipleObjects(5, ThreadHandle, TRUE, INFINITE);
DeleteCriticalSection(&cs);
printf("%d %d\r\n", m, n);
}
DWORD WINAPI ThreadProc(LPVOID Param)
{
CRITICAL_SECTION cs;
EnterCriticalSection(&::cs); //注意(&::cs)
for (int i=0;i<10000;i++)
{
m++;
n++;
}
LeaveCriticalSection(&::cs); //注意(&::cs)
return 0;
}