新建一个线程并且设置为立即执行的话为什么还要等主线程执行几行之后才开始运行?
#include<stdio.h>#include<windows.h>//线程函数DWORDWINAPIThreadProc(LPVOIDlpParam){inti=0...
#include <stdio.h>
#include <windows.h>
// 线程函数
DWORD WINAPI ThreadProc(LPVOID lpParam)
{
int i = 0;
while(i < 20)
{
printf(" I am from a thread, count = %d \n", i++);
}
return 0;
}
int main(int argc, char* argv[])
{
HANDLE hThread;
DWORD dwThreadId;
// 创建一个线程
hThread = ::CreateThread (
NULL, // 默认安全属性
NULL, // 默认堆栈大小
ThreadProc, // 线程入口地址(执行线程的函数)
NULL, // 传给函数的参数
0, // 指定线程立即运行
&dwThreadId); // 返回线程的ID号
printf(" Now another thread has been created1. ID = %d \n", dwThreadId);
printf(" Now another thread has been created2. ID = %d \n", dwThreadId);
printf(" Now another thread has been created3. ID = %d \n", dwThreadId);
printf(" Now another thread has been created4. ID = %d \n", dwThreadId);
printf(" Now another thread has been created5. ID = %d \n", dwThreadId);
printf(" Now another thread has been created6. ID = %d \n", dwThreadId);
printf(" Now another thread has been created7. ID = %d \n", dwThreadId);
// 等待新线程运行结束
::WaitForSingleObject (hThread, INFINITE);
::CloseHandle (hThread);
return 0;
}
上面这段代码,每次都是Now another thread has been created7显示完之后才显示线程的内容,线程创建并立即执行之后不是应该和主线程交替执行了吗?应该是主线程显示的内容和新线程显示的内容交替出现才对吧,为什么每次都是主线程的内容完全显示完之后才显示新线程的内容?? 展开
#include <windows.h>
// 线程函数
DWORD WINAPI ThreadProc(LPVOID lpParam)
{
int i = 0;
while(i < 20)
{
printf(" I am from a thread, count = %d \n", i++);
}
return 0;
}
int main(int argc, char* argv[])
{
HANDLE hThread;
DWORD dwThreadId;
// 创建一个线程
hThread = ::CreateThread (
NULL, // 默认安全属性
NULL, // 默认堆栈大小
ThreadProc, // 线程入口地址(执行线程的函数)
NULL, // 传给函数的参数
0, // 指定线程立即运行
&dwThreadId); // 返回线程的ID号
printf(" Now another thread has been created1. ID = %d \n", dwThreadId);
printf(" Now another thread has been created2. ID = %d \n", dwThreadId);
printf(" Now another thread has been created3. ID = %d \n", dwThreadId);
printf(" Now another thread has been created4. ID = %d \n", dwThreadId);
printf(" Now another thread has been created5. ID = %d \n", dwThreadId);
printf(" Now another thread has been created6. ID = %d \n", dwThreadId);
printf(" Now another thread has been created7. ID = %d \n", dwThreadId);
// 等待新线程运行结束
::WaitForSingleObject (hThread, INFINITE);
::CloseHandle (hThread);
return 0;
}
上面这段代码,每次都是Now another thread has been created7显示完之后才显示线程的内容,线程创建并立即执行之后不是应该和主线程交替执行了吗?应该是主线程显示的内容和新线程显示的内容交替出现才对吧,为什么每次都是主线程的内容完全显示完之后才显示新线程的内容?? 展开
2014-04-07
展开全部
主线程的代码太少了,所以很快就能执行完,如果多的话,就切换执行了!
2014-04-07
展开全部
码农?
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询