VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > Objective-C编程 >
  • 多线程MultiThread.cpp

制作者:剑锋冷月 单位:无忧统计网,www.51stat.net
  // MultiThread.cpp : 定义控制台应用程序的入口点。
//
  
#include "stdafx.h"
#include <windows.h>
#include <iostream>
  
using namespace std;
int tickets = 100;
HANDLE hMutex;
  
DWORD WINAPI Fun1Proc(LPVOID lp);
DWORD WINAPI Fun2Proc(LPVOID lp);
  
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread1,hThread2;
hThread1 = CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2 = CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
hMutex = CreateMutex(NULL,FALSE,NULL);
  
Sleep(2000);
system("pause");
return 0;
}
  
DWORD WINAPI Fun1Proc(LPVOID lp)
{
while(1)
{
 WaitForSingleObject(hMutex,INFINITE);
 if(tickets > 0)
 {
 Sleep(10);
 cout << "thread1 sell ticket." << tickets-- <<endl;
 }
 else
 break;
 ReleaseMutex(hMutex);
}
return 0;
}
  
DWORD WINAPI Fun2Proc(LPVOID lp)
{
while(1)
{
 WaitForSingleObject(hMutex,INFINITE);
 if(tickets > 0)
 cout << "thread2 sell ticket." << tickets-- <<endl;
 else
 break;
 ReleaseMutex(hMutex);
}
return 0;
}
 


相关教程