- ·上一篇内容:因打扑克出错牌引发命案
- ·下一篇内容:规则漏洞被利用!淘宝客隐性引流年赚数十万(转载)
C++多线程的例子
在多线程的程序里,不同的线程可以做不同的事情,下面演示一个多线程的例子。
// 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;
}