#include "stdafx.h"
#include <Windows.h>
#include <iostream>
using namespace std;
DWORD WINAPI ThreadFuncFirst(LPVOID param)
{
int iCount = 50;
while(iCount--){
cout<<"\nThreadFuncFirst:"<<iCount;
}
return 0;
}
DWORD WINAPI ThreadFuncSecond(LPVOID param)
{
int iCount = 50;
while(iCount--){
cout<<"\nThreadFuncSecond:"<<iCount;
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
DWORD dwThreadID = 0;
HANDLE handleFirst = CreateThread(NULL, 0, ThreadFuncFirst, 0, 0, &dwThreadID);
if (!handleFirst)
{
cout<<"create thread 1 error:"<<endl;
}
HANDLE handleSecond = CreateThread(NULL, 0, ThreadFuncSecond, 0, 0, &dwThreadID);
if (!handleSecond)
{
cout<<"create thread 2 error:"<<endl;
}
//HANDLE arrayHandle[] = {handleFirst, handleSecond};
//WaitForMultipleObjects(2, arrayHandle, TRUE, INFINITE);
WaitForSingleObject(handleFirst, INFINITE);//等待線程返回,用sleep()就太山寨了
WaitForSingleObject(handleSecond, INFINITE);
CloseHandle(handleFirst);//句柄默認值2 這里減1,線程函數執行完后釋放資源。
CloseHandle(handleSecond);
return 0;
}
另外,由於這里的兩個線程函數在輸出時沒有加同步處理,所以輸出時候有線程切換,你看到屏幕上的輸出可能比較雜亂。