线程同步: 让线程协同步调,按照一定的先后次序来执行
当人工重置的事件得到通知时,等待该事件的所有线程均变为可调度线程。
当一个自动重置的事件得到通知时,等待该事件的线程中只有一个线程变为可调度线程。
参考:
多线程与事件对象
多线程编程(13) - 多线程同步之 Event (事件对象)
#include <windows.h>
#include <iostream>
using namespace std;
DWORD WINAPI Fun1Proc(
LPVOID lpParameter // thread data
);
DWORD WINAPI Fun2Proc(
LPVOID lpParameter // thread data
);
int tickets = 100;
HANDLE g_hEvent;
void main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1 = CreateThread(NULL, 0, Fun1Proc, NULL, 0, NULL);
hThread2 = CreateThread(NULL, 0, Fun2Proc, NULL, 0, NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
g_hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);//自动的、无信号状态
SetEvent(g_hEvent);//设置事件信号为触发
Sleep(4000);
}
DWORD WINAPI Fun1Proc(
LPVOID lpParameter // thread data
)
{
while (TRUE)
{
WaitForSingleObject(g_hEvent, INFINITE);
if (tickets>0)
{
Sleep(1);
cout << "thread1 sell ticket : " << tickets << endl;
tickets--;
}
else
break;
SetEvent(g_hEvent);
}
return 0;
}
DWORD WINAPI Fun2Proc(
LPVOID lpParameter // thread data
)
{
while (TRUE)
{
WaitForSingleObject(g_hEvent, INFINITE);
if (tickets>0)
{
Sleep(1);
cout << "thread2 sell ticket : " << tickets << endl;
tickets--;
}
else
break;
SetEvent(g_hEvent);
}
return 0;
}