_endthreadex与CloseHandle

转自:http://bbs.csdn.net/topics/340008167

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()

 


 

    _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 );
}

转载于:https://www.cnblogs.com/qinfengxiaoyue/archive/2013/04/28/3048336.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值