#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;
}
另外,由于这里的两个线程函数在输出时没有加同步处理,所以输出时候有线程切换,你看到屏幕上的输出可能比较杂乱。
win32多线程 (一) 线程创建与结束等待,布布扣,bubuko.com
原文地址:http://www.cnblogs.com/zhidao-chen/p/3851526.html