///event
#include<windows.h>
#include<iostream>
/////已事件的形式 来处理线程同步。
using namespace std;
DWORD WINAPI Fun1Proc(LPVOID lpParameter);
DWORD WINAPI Fun2Proc(LPVOID lpParameter);
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);
if (g_hEvent)
{
if (ERROR_ALREADY_EXISTS == GetLastError())
{
cout << "only instance can run!"<<endl;
return;
}
}
SetEvent(g_hEvent);
Sleep(4000);
//CloseHandle(g_hEvent);
}
DWORD WINAPI Fun1Proc(LPVOID lpParameter)
{
while (1)
{
//SetEvent(g_hEvent);
WaitForSingleObject(g_hEvent,INFINITE);
if (tickets > 0)
{
Sleep(2);
cout << "Thread1 sell Tickets!" << tickets-- << endl;
}
else
{
break;
}
//ReleaseMutex(g_hEvent);
//ResetEvent(g_hEvent);
SetEvent(g_hEvent);
}
return 0;
}
DWORD WINAPI Fun2Proc(LPVOID lpParameter)
{
while (1)
{
//SetEvent(g_hEvent);
WaitForSingleObject(g_hEvent, INFINITE);
if (tickets > 0)
{
Sleep(1);
cout << "Thread2 sell Tickets!" << tickets-- << endl;
}
else
{
break;
}
//ReleaseMutex(g_hEvent);
//ResetEvent(g_hEvent);
SetEvent(g_hEvent);
}
return 0;
}
///Critical
#include<windows.h>
#include<iostream>
/////已事件的形式 来处理线程同步。
using namespace std;
DWORD WINAPI Fun1Proc(LPVOID lpParameter);
DWORD WINAPI Fun2Proc(LPVOID lpParameter);
int tickets = 100;
HANDLE g_hEvent;
CRITICAL_SECTION g_Cs;
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);
InitializeCriticalSection(&g_Cs);
Sleep(4000);
//CloseHandle(g_hEvent);
DeleteCriticalSection(&g_Cs);
}
DWORD WINAPI Fun1Proc(LPVOID lpParameter)
{
while (1)
{
EnterCriticalSection(&g_Cs);
if (tickets > 0)
{
Sleep(2);
cout << "Thread1 sell Tickets!" << tickets-- << endl;
}
else
{
break;
}
LeaveCriticalSection(&g_Cs);
}
return 0;
}
DWORD WINAPI Fun2Proc(LPVOID lpParameter)
{
while (1)
{
EnterCriticalSection(&g_Cs);
if (tickets > 0)
{
Sleep(1);
cout << "Thread2 sell Tickets!" << tickets-- << endl;
}
else
{
break;
}
LeaveCriticalSection(&g_Cs);
}
return 0;
}