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;
}
另外,由于这里的两个线程函数在输出时没有加同步处理,所以输出时候有线程切换,你看到屏幕上的输出可能比较杂乱。
#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多线程之等待一个线程的结束(WaitForSingleObject)
- 线程创建,属性设置与获得,等待线程结束,线程中fork,以及执行exec()
- 控制台创建两个线程,等待一个线程的结束,执行另外一线程
- WIN32多线程一 用WIN32 API创建和结束线程(转)
- VC++等待线程结束的方法
- vc 线程的创建,暂停和结束
- 异步回调 主线程等待子线程结束
- 等待一个线程的结束
- 嵌入式Linux应用程序开发——多线程1(线程的创建和等待)
- 在你的服务器端代码中使用线程和创建异步处理(结束)
- [原] 主线程等待子线程结束(多线程结束标识)
- linux下线程的创建和等待
- passcal 多线程例子,线程管理,创建,暂停,中止,等待等。。。
- 【Win32多线程】创建线程、获取线程执行状态、退出线程、错误处理
- 主线程中使用join等待所有子线程执行结束
- 创建线程和结束线程
- 线程的创建和结束的方法
- 创建线程,互斥线程,非互斥线程及线程的结束
- C#窗口中创建了线程,关闭窗口,进程无法结束的问题
- 【Win32多线程】如何避免线程等待浪费CPU时间,降低对系统资源的冲击?