_endthreadex与CloseHandle的区别

mqywda 2010-05-02 06:48:28

int main()
{
HANDLE handle= (handle)_beginthreadex(0,0,ThreadFunc,(void*),0,0);
CloseHandle(handle)//请问这句还需要吗
}
unsigned WINAPI ThreadFunc(LPVOID pData)
{
................................
_endthreadex(0);//这里已经关闭了
}


...全文
1183 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
向立天 2010-05-02
  • 打赏
  • 举报
回复
CloseHandle(handle);的作用是释放点handle这个线程内核对象,这个操作告诉操作系统我们对于这个线程的统计信息已经不再关心了,不过这个操作并不会结束线程
_endthreadex(0);会结束线程,其中0是这个线程的返回码
zyq5945 2010-05-02
  • 打赏
  • 举报
回复
http://www.cnblogs.com/lgxqf/archive/2009/02/10.html
4.线程内部细节

1.CreateThread 和 _beginthreadex 区别:



CreateThread是系统API,_beginthreadex是CRT(C Run Time Library 运行时库)函数. _beginthreadex内部会调用CreateThread函数。

_endthreadex会释放_beginthreadex为tiddata结构分配的内存。



如果线程函数中调用了CRT函数(注:不是全部CRT函数 只是其中一部分函数),则该线程函数必须由_beginthreadex而不是CreateThread函数创建。否则会产生内存泄露。

如果在除主线程之外的任何线程中进行一下操作,你就应该使用多线程版本的C runtime library,并使用_beginthreadex和_endthreadex:

(1) 使用malloc()和free(),或是new和delete

(2) 使用stdio.h或io.h里面声明的任何函数

(3) 使用浮点变量或浮点运算函数

(4) 调用任何一个使用了静态缓冲区的runtime函数,比如:asctime(),strtok()或rand()



2._beginthreadex和_beginthread区别



_beginthreadex内部会自动调用 _endthreadex.

_beginthread内部会自动调用_endthread.



_endthread内部会自动调用CloseHandle关闭当前Thread内核对象的句柄,所以在用_beginthread 时我们不需要在主线程中调用CloseHandle来关闭子线程的句柄。

_endthreadex相比_endthread而言更安全。它不会自动关闭当前Thread内核对象的句柄。所以在用_beginthreadex时我们需要用CloseHandle来关闭子线程的句柄。
MSDN中的例子
// crt_begthrdex.cpp
// compile with: /MT
#include <windows.h>
#include <stdio.h>
#include <process.h>

unsigned Counter;
unsigned __stdcall SecondThreadFunc( void* pArguments )
{
printf( "In second thread...\n" );

while ( Counter < 1000000 )
Counter++;

_endthreadex( 0 );
return 0;
}

int main()
{
HANDLE hThread;
unsigned threadID;

printf( "Creating second thread...\n" );

// Create the second thread.
hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc, NULL, 0, &threadID );

// Wait until second thread terminates. If you comment out the line
// below, Counter will not be correct because the thread has not
// terminated, and Counter most likely has not been incremented to
// 1000000 yet.
WaitForSingleObject( hThread, INFINITE );
printf( "Counter should be 1000000; it is-> %d\n", Counter );
// Destroy the thread object.
CloseHandle( hThread );
}

16,548

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • AIGC Browser
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

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