#include "stdafx.h"


#include <iostream>
using namespace std;


#include "windows.h"

int index = 0;
int tickets = 100;
HANDLE hMutex = NULL; //互斥
HANDLE hEvent = NULL; //事件

CRITICAL_SECTION g_cs ; //临界区


DWORD WINAPI Func1(LPVOID pParam)
{

while(true)

{

// WaitForSingleObject(hMutex, INFINITE);

WaitForSingleObject(hEvent,INFINITE);

// EnterCriticalSection(&g_cs);

if(tickets> 0)

{

Sleep(1);

cout<<"thread1 sell tickets:"<<tickets--<<endl;

}

else

break;

// ReleaseMutex(hMutex);

SetEvent(hEvent);

// LeaveCriticalSection(&g_cs);

}

return 0;

}

DWORD WINAPI Func2(LPVOID pParam)

{

while(true)

{

// WaitForSingleObject(hMutex,INFINITE);

WaitForSingleObject(hEvent,INFINITE);

// EnterCriticalSection(&g_cs);

if(tickets> 0)

{

Sleep(1);

cout<<"thread2 sell tickets:"<<tickets--<<endl;

}

else

break;

// ReleaseMutex(hMutex);

SetEvent(hEvent);

// LeaveCriticalSection(&g_cs);

}

return 0;

}

void main()

{

HANDLE hThread1 =CreateThread(NULL, 0, Func1, NULL, 0, NULL);

HANDLE hThread2 =CreateThread(NULL, 0, Func2, NULL, 0, NULL);

CloseHandle(hThread1);

CloseHandle(hThread2);

//hMutex = CreateMutex(NULL,FALSE,NULL);

hEvent =CreateEvent(NULL, FALSE, TRUE,NULL);

//InitializeCriticalSection(&g_cs);

Sleep(4000);

//DeleteCriticalSection(&g_cs);

}

posted on 2015-03-18 18:31  冷风少年  阅读(559)  评论(0编辑  收藏  举报