CreateThread vs _beginthreadex

I just finished episode 122 so forgive me if this has already been answered. I've been reading a book on Windows systems programming and on the chapter of threading the author suggests avoiding the use of CreateThread if the application is using the CRT. He instead suggests to use _beginthreadex and linking to a multithreaded CRT. Handmade Hero is not really using the CRT as far as I understand, however, I was wondering what the actual difference between the 2 function families is, and which one should be used in production code.
I have never had a problem using CreateThread, but that is probably because I don't generally use the CRT for anything. It may be that the CRT needs to set up some special things for each thread that gets created that might call certain CRT functions. So if you plan on making extensive use of the CRT, it may indeed be wise to call their thread creation routines directly instead of using the Windows system calls.

- Casey
For last few versions of Visual Studio (at least from VS2005, maybe even older) all CRT functions relies on some special things being set up in _beginthreadex. Any CRT function that relies on this stuff will check if that was done and in case if that was not done (if you used CreateThread) it will set everything up. So you don't need to worry about using CreateThread vs _beginthreadex.

If you are not using CRT then using CreateThread will actually be a bit faster and using less memory - because you won't be setting up CRT stuff you don't use.


To see this in actual CRT source you can examine "strtok" function implementation. As you know strtok stores in internal state some information about next token. So for every thread it should be different. This is achieved by TLS. If you look at "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\crt\src\strtok.c" source file you'll notice
1
_ptiddata ptd = _getptd();
statement.

You can find _getptd function in "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\crt\src\tidtable.c" file:
1
2
/***
*_ptiddata _getptd(void) - get per-thread data structure for the current thread


It's implementation executes following code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
    if ( (ptd = __crtFlsGetValue(__flsindex)) == NULL ) {
        /*
         * no per-thread data structure for this thread. try to create
         * one.
         */
        ...
    }

    ...

    return(ptd);

As you can see - it checks if per-thread structure for this thread is allocated and if not it allocates new one.

Edited by Mārtiņš Možeiko on
Ah I see. Thank you both for the explanation.