程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> 多線程MultiThread.cpp

多線程MultiThread.cpp

編輯:關於C++

// 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;
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved