11

What is the difference between CreateThread and beginthread APIs in Windows? Which one is preferrable for thread creation?

Serge Wautier
  • 21,494
  • 13
  • 69
  • 110
Jay
  • 24,173
  • 25
  • 93
  • 141

1 Answers1

16

_beginthread() and _beginthreadex() was required by earlier versions of the Microsoft CRT to initialize thread-local state. The strtok() function would be an example. That's been fixed, that state now gets dynamically initialized, at least since VS2005. Using CreateThread() no longer causes problems.

Serge Wautier
  • 21,494
  • 13
  • 69
  • 110
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 1
    Yes - if a thread is created using `CreateThread()` then `strtok()` will allocate the per-thread-data block. However when the thread exits, that block will be leaked. Might not be a big deal, but why not just use `_beginthreadex()` in the first place? Also, for the new "packaged applications", `_beginthreadex()` (from VS 2012) will make sure the MTA is initialized in the new thread. Why not have programmers get into the habit of using `_beginthreadex()` (which really has no downside compared to using `CreateThread()` - it even has basically the same signature). – Michael Burr Jan 28 '13 at 08:43
  • @Michael - check the CRT source code, look for the way it uses FlsAlloc() to install a callback to release memory. Not being able to use the CRT in threadpool threads is of course not an acceptable limitation. – Hans Passant Jan 28 '13 at 08:49