As 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)


comments powered by Disqus