您的位置:首页 > 其它

win32多线程 (一) 线程创建与结束等待

2014-07-17 17:01 393 查看
#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;
}

另外,由于这里的两个线程函数在输出时没有加同步处理,所以输出时候有线程切换,你看到屏幕上的输出可能比较杂乱。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: