Creating threads in Win32 C/C++ programming
January 28th, 2009 at 8:00 pmAs I was reading a book about client-server programming, I saw that the author was using the _beginthread function from process.h for creating threads on Windows. Wait a second, I thought, this is wrong – CreateThread should be used to create threads. NOT!
It turns out that when you write C/C++ code using the Windows API, you should always use _beginthread & _beginthreadex over CreateThread. Always! This MSDN Q&A provides a great discussion, and there are more details online if you google _beginthreadex vs. CreateThread.
In short, the main reason is that the C runtime (CRT) is not thread safe. Two of the most notable examples are the errno variable and strtok. So, if you just call CreateThread – your code may behave weirdly if it uses the non thread-safe features of the CRT.
However, if you compile your program with the multi-threaded (MT) version of the CRT (supplied by Microsoft with Visual Studio) and then use _beginthreadex instead of CreateThread – all CRT operations will be thread-safe, because _beginthreadex starts by dynamically allocating a Thread Local Storage (TLS) data structure which holds all those evil global variables, and the functions of the MT CRT know to access this data structure instead of globals.
Oh, and if you’re saying to yourself "I don’t need this, I don’t use all those stinkin’ non thread-safe functions", think again. When you compile your Windows application with the single-threaded CRT, even malloc isn’t thread-safe! So just compile with MT and use _beginthreadex in any case, do yourself a favor.
To compile with the MT CRT, make sure that the Runtime Library option in C&C++ -> Code Generation page in your MSVC project settings is set to Multi-threaded (/MT)
Related posts:

January 28th, 2009 at 21:44
Another favour you can make to yourself is to move to a decent VC version, like 2005 or 2008
VC6 and its horrible mess with MT/MD is dead
January 29th, 2009 at 22:38
@Pierre,
I’m not sure I’m following you. I haven’t touched VC6 for years. The experience expressed here is about VS 2005
January 30th, 2009 at 01:34
2005 and later have only a threaded CRT. You can choose single threaded CRT as in VC6. It is a good thing as it was a pain to deal with the different crt flags
The MT or MD flag are something else, it is to define how the crt should be linked, static (mt) dynamic (md), mdd or mtd(debug or non debug) linking the CRT.
See http://msdn.microsoft.com/en-us/library/2kzt1wy3.aspx
January 30th, 2009 at 10:06
Interesting. Thanks for the information.