步骤:
1、 用Microsoft Visual Studio 2005创建控制台项目HelloThreads 。
2、 创建HelloThreads.cpp文件
3、点击项目—>HelloThreads属性菜单,按图1-1~图1-4配置项目属性。
4、编译执行,输出结果:
5、修改代码,使之输出结果可以表示出各线程的输出顺序。
// HelloThreads.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <Windows.h>
#include <stdio.h>
const int numThreads = 4;
DWORD WINAPI helloFunc(LPVOID pArg)
{
int j = *(int*)pArg;
printf("Hello Thread %d\n",j);
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread[numThreads];
int tNum[4];
for (int i = 0; i < numThreads; i++)
{
tNum[i] = i;
hThread[i] = CreateThread(NULL, 0, helloFunc, &tNum[i], 0, NULL);
}
WaitForMultipleObjects(numThreads, hThread, TRUE, INFINITE);
system("pause");
return 0;
}