近期工作中用到了Windows中的線程創建函數,實例代碼如下:
#include <QCoreApplication>
#include <windows.h>
#include <iostream>
#include <windef.h>
using namespace std;
//聲明瞭兩個線程處理函數
DWORD WINAPI Fun1Proc(LPVOID lpParameter);
DWORD WINAPI Fun2Proc(LPVOID lpParameter);
//公有變量作爲共享資源
int tickets=100;
//互斥鎖句柄
HANDLE hMutex;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
HANDLE hThread1;
HANDLE hThread2;
//創建互斥鎖
hMutex=CreateMutex(NULL,FALSE,NULL);
//使用CreateThread函數創建線程hThread1和hThread2
hThread1=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)Fun1Proc,NULL,0,NULL);
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
while(true)
{
//主線程在互斥鎖中出售火車票
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
cout<<"main thread sell ticket:"<<tickets--<<endl;
else
break;
ReleaseMutex(hMutex);
}
return 0;
//銷售完火車票後關閉兩個子線程
CloseHandle(hThread1);
CloseHandle(hThread2);
Sleep(4000);
return a.exec();
}
//線程hThread1的線程處理函數
DWORD WINAPI Fun1Proc(LPVOID lpParameter)
{
while(true)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
cout<<"thread1 sell ticket:"<<tickets--<<endl;
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
//線程hThread2的線程處理函數
DWORD WINAPI Fun2Proc(LPVOID lpParameter)
{
while(true)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
cout<<"thread2 sell ticket:"<<tickets--<<endl;
else
break;
ReleaseMutex(hMutex);
}
return 0;
}