關於線程函數結束前顯式調用_endthreadex

來源:互聯網
上載者:User

1. 本來,MSDN已經明確指出了:

You can call _endthread or _endthreadex explicitly to terminate a thread; however, _endthread or _endthreadex is

called automatically when the thread returns from the routine passed as a parameter to_beginthread or

_beginthreadex. Terminating a thread with a call toendthread or _endthreadex helps ensure proper recovery of

resources allocated for the thread(http://msdn.microsoft.com/en-us/library/vstudio/hw264s73.aspx).

即,線程從線程函數(常式)返回後,將自動調用_endthreadex. 意即不必線上程函數返回前顯式調用_endthreadex.

而在樣本_beginthreadex函數時,MSDN給出了如下例子(http://msdn.microsoft.com/en-us/library/kdzttdcb(v=VS.80).aspx):

unsigned Counter; unsigned __stdcall SecondThreadFunc( void* pArguments ){    printf( "In second thread...\n" );    while ( Counter < 1000000 )        Counter++;    _endthreadex( 0 );    return 0;} 

2. 到底要不線上程函數前調用_endthreadex呢?

MSDN在對_endthreadex的註解中提到:

_endthread and _endthreadex cause C++ destructors pending in the thread not to be called.

意即線上程中調用_endthreadex,會導致C++對象的解構函式掛起而不被調用。如果線上程函數中產生的對象關乎資源分派,則可能引起資

源不能被正常回收(destructor不被調用)。

相關資料:

http://stackoverflow.com/questions/9090143/shouldnt-i-use-endthreadex-in-thread-procedure-for-stack-unwinding

http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.kernel/2005-05/msg00096.html

而如果非要用怎麼辦?

如下例(http://blog.chinaunix.net/uid-406135-id-3421540.html):

在MSDN的樣本中,線程函數結束都有

    _endthreadex( 0 );

    return 0;


以前,我一直不加_endthreadex( 0 ),因為覺得它很醜很冗餘,MSDN上如是說:

_endthread or _endthreadex is called automatically when the thread returns from the routine passed as a parameter.

也就是它屁用沒有,假如我寫成:

    _endthreadex( 0 );

    return 1;

還會引起歧義。

今日我一時興起,在return前加上了 _endthreadex( 0 ),然後就報記憶體泄露,因為它中止線程前不會析構局部變數。

於是將代碼改為:

unsigned __stdcall foo( void* p )

{

    {

        //這裡是執行代碼

    }

    _endthreadex( 0 );

    return 0;

}

也就是加了個似乎沒用的{}。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.