网易公开课,一个多线程的例子,VC2010控制台程序测试通过。
// 一个飞机票售票的实现。
//
//
#include "stdafx.h"
#define AGENTNUM 3
HANDLE hSemaphore;
typedef struct _THREADDATA
{
int agent;
int *numTickets;
}*LPTHREADDATA, THREADDATA;
DWORD _stdcall SellTickets(LPVOID lpParameter);
HANDLE hSemaphore;
typedef struct _THREADDATA
{
int agent;
int *numTickets;
}*LPTHREADDATA, THREADDATA;
DWORD _stdcall SellTickets(LPVOID lpParameter);
int main(int argc, char* argv[])
{
int agentnum = AGENTNUM;
int numTickets = 10;
HANDLE handle[AGENTNUM];
hSemaphore = CreateSemaphore(NULL, 1, 1, NULL);
LPTHREADDATA agentdata = new THREADDATA[AGENTNUM];
for(int i=0;i<agentnum;i++) {
agentdata[i].agent = i+1;
agentdata[i].numTickets = &numTickets;
handle[i] = CreateThread(NULL, 1,SellTickets, &agentdata[i], 0, NULL);
}
WaitForMultipleObjects(AGENTNUM,handle,TRUE,INFINITE);
delete(agentdata);
return 0;
}
{
int agentnum = AGENTNUM;
int numTickets = 10;
HANDLE handle[AGENTNUM];
hSemaphore = CreateSemaphore(NULL, 1, 1, NULL);
LPTHREADDATA agentdata = new THREADDATA[AGENTNUM];
for(int i=0;i<agentnum;i++) {
agentdata[i].agent = i+1;
agentdata[i].numTickets = &numTickets;
handle[i] = CreateThread(NULL, 1,SellTickets, &agentdata[i], 0, NULL);
}
WaitForMultipleObjects(AGENTNUM,handle,TRUE,INFINITE);
delete(agentdata);
return 0;
}
DWORD _stdcall SellTickets(LPVOID lpParameter)
{
while(TRUE) {
WaitForSingleObject(hSemaphore, INFINITE);
LPTHREADDATA pData = (LPTHREADDATA)lpParameter;
if(*(pData->numTickets) == 0) break;
printf("子线程的线程ID号为:%d,售票点:%d,卖出机票编号:%d\n",GetCurrentThreadId(),pData->agent,*(pData->numTickets));
(*(pData->numTickets)) --;
ReleaseSemaphore(hSemaphore, 1, NULL);
if(rand()%3 <= 2 ) Sleep(500);
}
ReleaseSemaphore(hSemaphore, 1, NULL);
return 0;
}
{
while(TRUE) {
WaitForSingleObject(hSemaphore, INFINITE);
LPTHREADDATA pData = (LPTHREADDATA)lpParameter;
if(*(pData->numTickets) == 0) break;
printf("子线程的线程ID号为:%d,售票点:%d,卖出机票编号:%d\n",GetCurrentThreadId(),pData->agent,*(pData->numTickets));
(*(pData->numTickets)) --;
ReleaseSemaphore(hSemaphore, 1, NULL);
if(rand()%3 <= 2 ) Sleep(500);
}
ReleaseSemaphore(hSemaphore, 1, NULL);
return 0;
}