zoukankan      html  css  js  c++  java
  • _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 );
    }
  • 相关阅读:
    [No0000199]设计模式总结
    [No0000197]Windows用户都应该知道的运行命令
    [No000017F]如何监控注册表的修改
    [No0000196]一文读懂Java 11的ZGC为何如此高效
    [No0000195]NoSQL还是SQL?这一篇讲清楚
    [No0000194]聊聊 Chrome DevTools 中你可能不知道的调试技巧
    [No000018A]改善C#程序的建议11-20
    [No000018C]Vim清除上次的搜索高亮结果-Vim使用技巧(1)
    [No000018D]Vim快速注释/取消注释多行的几种方法-Vim使用技巧(2)
    [No000018E]Vim快速跳转任意行、任意列以及高亮显示当前行、当前列方法-Vim使用技巧(3)
  • 原文地址:https://www.cnblogs.com/qinfengxiaoyue/p/3048336.html
Copyright © 2011-2022 走看看