当前位置:编程学习 > C/C++ >>

多线程MultiThread.cpp

// MultiThread.cpp : 定义控制台应用程序的入口点。

//

#include "stbdafx.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;
}
 


作者:tbw
补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,