读书人

新线程运行有关问题

发布时间: 2012-03-03 15:33:03 作者: rapoo

新线程运行问题
#include <iostream>
#include <windows.h>

// 线程函数
DWORD WINAPI ThreadProc(LPVOID lpParam)
{
for(int i = 0; i != 20; ++i)
{
std::cout << " I am from a thread, count = " << i << std::endl;
}
return 0;
}

int main(int argc, char* argv[])
{
HANDLE hThread;
DWORD dwThreadId;

// 创建一个线程
hThread = ::CreateThread (
NULL,// 默认安全属性
NULL,// 默认堆栈大小
ThreadProc,// 线程入口地址(执行线程的函数)
NULL,// 传给函数的参数
0,// 指定线程立即运行
&dwThreadId);// 返回线程的ID号
std::cout << " Now another thread has been created. ID = " << dwThreadId << std::endl;

// 等待新线程运行结束
::WaitForSingleObject (hThread, INFINITE);
::CloseHandle (hThread);
return 0;
}

VS2008编译运行结果
Now another thread has been created. ID = I am from a thread, count = 23680

I am from a thread, count = 1
I am from a thread, count = 2
I am from a thread, count = 3
I am from a thread, count = 4
I am from a thread, count = 5
I am from a thread, count = 6
I am from a thread, count = 7
I am from a thread, count = 8
I am from a thread, count = 9
I am from a thread, count = 10
I am from a thread, count = 11
I am from a thread, count = 12
I am from a thread, count = 13
I am from a thread, count = 14
I am from a thread, count = 15
I am from a thread, count = 16
I am from a thread, count = 17
I am from a thread, count = 18
I am from a thread, count = 19
请按任意键继续. . .

以上代码为什么没输出"i = 0"?

[解决办法]
Now another thread has been created. ID = I am from a thread, count = 23680
在这里

读书人网 >VC/MFC

热点推荐