关于windows多线程的问题

hjl_heart 2017-10-27 11:41:12
int main()
{
HANDLE hThread1;
hThread1=CreateThread(NULL,0,Proc1,NULL,0,NULL);
CloseHandle(hThread1);
cout<<"main thread is running"<<endl;
//随着主线程的退出,进程结束了,线程1也就退出了
Sleep(10); //添加此语句可观察线程1和主线程并发执行
}
DWORD WINAPI Proc1(LPVOID lpParameter)
{
cout<<"thread1 is running"<<endl;
return 0;
}
请问以上程序执行后为什么会出现下面这种情况:
main thread is running
main thread is running
thread1 is running


新手不是很懂,希望有人能解答下,十分感激!
...全文
266 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
hjl_heart 2017-11-09
  • 打赏
  • 举报
回复
引用 2 楼 mamutu02 的回复:
引用
main thread is running main thread is running thread1 is running
这应该是两次的执行结果。 第一次执行的时候,程序中是没有这句话的:
Sleep(10); //添加此语句可观察线程1和主线程并发执行
得到的结果是:
引用
main thread is running
第二次执行的时候有上面那句Sleep,结果是:
引用
main thread is running thread1 is running
原因我想你也能明白。第一次执行的时候主线程退出,子线程还来不及打印" thread1 is running"就跟着一起退出了。第二次因为Sleep了10毫秒,子线程有时间将这句话打到屏幕上。。
没有。。。这是我执行一次的结果。。。我也知道你分析的东西,但总想不出为啥执行一次会出现这样的结果。 顺便说一下,这结果我是在一台旧电脑上(用的windows 7系统)用vc6.0运行出来的,但是我换了台新电脑(用的是windows10)运行就出现不了这样的结果
mamutu02 2017-10-30
  • 打赏
  • 举报
回复
引用
main thread is running main thread is running thread1 is running
这应该是两次的执行结果。 第一次执行的时候,程序中是没有这句话的:
Sleep(10); //添加此语句可观察线程1和主线程并发执行
得到的结果是:
引用
main thread is running
第二次执行的时候有上面那句Sleep,结果是:
引用
main thread is running thread1 is running
原因我想你也能明白。第一次执行的时候主线程退出,子线程还来不及打印" thread1 is running"就跟着一起退出了。第二次因为Sleep了10毫秒,子线程有时间将这句话打到屏幕上。。
赵4老师 2017-10-28
  • 打赏
  • 举报
回复
《Windows核心编程》

3,882

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 其它技术问题
社区管理员
  • 其它技术问题社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧