_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 );
}
posted on 2013-04-28 00:20  qinfengxiaoyue  阅读(3336)  评论(0编辑  收藏  举报