windows下线程何时开始、何时结束

本文详细阐述了线程从创建到结束的全过程,包括线程函数的执行、ExitThread和TerminateThread函数的作用,以及线程在进程结束时的终止方式。通过实际代码示例,展示了如何测试线程的状态与生命周期。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

1.线程何时开始:创建时候开始
2.何时结束:线程函数结束时候结束;到TerminateThread或者ExitThread时候退出,还有一种情况就是,在主线程或者线程所在进行结束的时候也结束(这里没有测试代码,但是可以通过在控制台main函数中创建一个线程,在线程处理函数中使用while(1),这样线程函数不会结束,但是再关掉这个进程的时候线程也不工作了来验证)。
测试代码如下:
#include <iostream>
#include <process.h>      //这个头文件中有CreateThread(),ExitThread(),CloseHandle()函数
#include <Windows.h>
#include <stdio.h>

using namespace std;

HANDLE handle;
DWORD dw;

DWORD WINAPI MyThread(void *p)
{
 cout << "My Thread ID:" << GetCurrentThreadId() << endl;
 
 GetExitCodeThread(handle,&dw);
 if (dw == STILL_ACTIVE)
  cout << "Thread Is Still Active!" << endl;
  
 /*while (STILL_ACTIVE == dw)
 {
 }*/

 //ExitThread(3);
 cout << "can go here now" << endl;
 Sleep(10000);
 
 return 0;
}

int main()
{
 handle = CreateThread(NULL,0,MyThread,NULL,0,&dw);
 Sleep(5000);//程序执行到这里延迟100毫秒(millionsecond)

 GetExitCodeThread(handle,&dw);
 if (dw != STILL_ACTIVE)
 {
  cout << "Exit Code is:" << dw << endl;
 }
 else
 {
  cout << "Thread Is Still Active!" << endl;
 }
 Sleep(6000);
 GetExitCodeThread(handle,&dw);
 if (dw != STILL_ACTIVE)
 {
  cout << "Exit Code is:" << dw << endl;
 }
 else
 {
  cout << "Thread Is Still Active!" << endl;
 }

 CloseHandle(handle);
 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值