创建线程的方法(windows)

引用:windows程序员面试指南

windows上常用的创建线程的方法:CreateThread(),_beginthread(),std::thread

1.CreateThread()

CreateThread 是 windows 提供的 api,用法如下:

HANDLE CreateThread(
  [in, optional]  LPSECURITY_ATTRIBUTES   lpThreadAttributes,
  [in]            SIZE_T                  dwStackSize,
  [in]            LPTHREAD_START_ROUTINE  lpStartAddress,
  [in, optional]  __drv_aliasesMem LPVOID lpParameter,
  [in]            DWORD                   dwCreationFlags,
  [out, optional] LPDWORD                 lpThreadId
);

注意:默认情况下,每个线程都有 1MB 的堆栈空间

2._beginthread() 和 _beginthreadex()

uintptr_t _beginthread( // NATIVE CODE
   void( __cdecl *start_address )( void * ),
   unsigned stack_size,
   void *arglist
);
uintptr_t _beginthread( // MANAGED CODE
   void( __clrcall *start_address )( void * ),
   unsigned stack_size,
   void *arglist
);
uintptr_t _beginthreadex( // NATIVE CODE
   void *security,
   unsigned stack_size,
   unsigned ( __stdcall *start_address )( void * ),
   void *arglist,
   unsigned initflag,
   unsigned *thrdaddr
);
uintptr_t _beginthreadex( // MANAGED CODE
   void *security,
   unsigned stack_size,
   unsigned ( __clrcall *start_address )( void * ),
   void *arglist,
   unsigned initflag,
   unsigned *thrdaddr
);

注意:若要使用 _beginthread 或 _beginthreadex,应用程序必须与一个多线程 C 运行库链接。

CreateThread()和_beginthread()的区别

1.库的不同:CreateThread是Windows API的一部分,而_beginthread是C运行库(CRT)中的函数。这意味着_beginthread可以在C或C++程序中通过包含相应的头文件来使用,而CreateThread则需要通过包含processthreadsapi.h头文件来使用。
2.线程对象的处理:使用CreateThread创建的线程在终止后,线程对象仍然存在于系统中,需要显式地通过调用CloseHandle来关闭该线程对象。而使用_beginthread创建的线程,在调用_endthread后会自动销毁线程对象,无需手动关闭。
3.对CRT库的兼容性:如果在线程中使用CRT库,应该使用_beginthread而不是CreateThread。这是因为CreateThread不会判断传递给它的起始地址lpStartAddr是数据还是代码,也不会判断是否有足够的访问权限。这可能导致类成员函数或非函数指针的强制转换,以及栈溢出和访问权限问题。此外,如果在线程中使用类成员函数,需要注意this指针的正确传递。而在类对象外调用时,this指针可能是未知的。
4.内存泄漏:在使用CRT函数时,如果在CreateThread创建的线程中使用CRT函数,可能会导致内存泄漏。而在_beginthread创建的线程中使用CRT函数通常不会产生内存泄漏问题。

3.std::thread

C++11,添加 std::thread
常用方法:
get_id 获取线程 ID。
joinable 检查线程是否可被 join。
join 阻塞,等待线程结束。
detach 线程分离
swap Swap 线程 。
native_handle 返回 native handle。
hardware_concurrency [static] 检测硬件并发特性

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值