Click here to Skip to main content
12,898,663 members (67,879 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


2 bookmarked
Posted 6 Sep 2011

Is it mandatory to call _endthreadex() in your thread function?

, 3 Oct 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
Do you really need an explicit call to _endthreadex() in your thread function created using _beginthreadex()
I have often seen the thread functions written like the one below:

DWORD WINAPI MyThreadProc( LPVOID lpParam )
    _endthreadex( 0 );  // This is the thing in QUESTION!!!
    return 0; // This part will never be executed, as _endthreadex() calls // ExitThread() with the value passed to _endthreadex()

Do we really require to call _endthreadex() in the threads created using _beginthreadex()? A big NO is the answer!! and for that matter you don't need a call to ExitThread() too.

_beginthreadex() function actually allocates and initializes the per thread data required by the CRT and calls CreateThread() passing a stub function in CRT as the entrypoint for the thread. This stub function will call your actual thread function(in this case, MyThreadProc) and when your thread function returns, the stub function ensures that it calls _endthreadex() passing the value returned from the thread function.

Again in _endthreadex(), the per thread data allocated will be released and ExitThread() will be called passing the value received in _endthreadex().

Reference: threadex.c & thread.c in CRT Source.

Please be free to ask your queries, if any. :)


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Karthik Kalyanasundaram
Software Developer (Senior)
India India
Started my career as software engineer on May-21-2005. Worked on VC++ for first three months after that moved to .Net (MC++ and C#) for 19 months. Now back again to VC++.

Now doing some research in Win CE and Platform Builder.

You may also be interested in...


Comments and Discussions

GeneralReason for my vote of 5 this explains thread very simply Pin
kingoftheworld14-Oct-11 1:23
memberkingoftheworld14-Oct-11 1:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170424.1 | Last Updated 3 Oct 2011
Article Copyright 2011 by Karthik Kalyanasundaram
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid