Tuesday, June 20, 2006

On Windows, Why Should I Use _beginthreadex Instead of CreateThread/Ex to Create Threads?

In genral, using CreateThread is not thread safe. It is not because CreateThread/Ex is not thread safe itself, but because using it in applications linked with a CRT (C/C++ Run-Time) library is not. Two noticeable items:

1) The applications built on VC++ 6, regardless of type, have been linked to one of the CRT libraries shiped with VC++:

Single-Threaded (default)
Multithreaded
Multithreaded DLL
Debug Single-Threaded
Debug Multithreaded
Debug Multithreaded DLL

You could avoid calling CRT functions in your module, but you have no control over who, where and when CRT is used in the application.

2) For multithreaded C/C++ to work properly, a data structure must be created and associated with each thread that uses CRT functions. CreateThread is an OS call, but _beginthreaded is a CRT call. If you call CreateThread, OS doesn't know:
- your application is written in C/C++,
- you are calling functions that aren't natively thread-safe
- it needs to allocate a CRT data block for the new thread
When you call _beginthreaded, CRT knows and handles all these in a proper manner. Then, CRT calls CreateThread inside _beginthreaded to actually create the thread you wanted.

Jeffery Richter's classic text "Programming Applications for Microsoft Windows" (4th Ed.) Chapter 6 has explained this in more detail.

0 Comments:

Post a Comment

<< Home