简体   繁体   中英

Question about Windows API and C/C++ run-time library function

When I write C/C++ code for Windows platform, I usually use Windows APIs as necessary. But when it comes to multi-threading, I read the following quotaion from < Windows via C/C++ >

The CreateThread function is the Windows function that creates a thread. However, if you are writing C/C++ code, you should never call CreateThread. Instead, you should use the Microsoft C++ run-time library function _beginthreadex. If you do not use Microsoft's C++ compiler, your compiler vendor will have its own alternative to CrateThread. Whatever this alternative is, you must use it.

AFAIK, a language run-time library for a certain platform is implemented with that platform's APIs. I think it is totally possible to call CreateThread() from my C/C++ code. And I quite did that. But I just don't understand why the above rule should be followed.

Many thanks for your insights.

Of course it's possible to use the Windows API's CreateThread directly.

But that leaves the runtime library uninformed about the new thread.

For the multi-threading support in the runtime library (and that includes functions that rely on static storage, eg I imagine it includes strtok ) you need to keep the runtime library informed, and not only informed, but partially in charge so that eg failure to allocate whatever resources it needs for a thread, results in thread creation failure.

Cheers & hth.,

The c-runtime has numerous stateful variables that hold things, such as the current locale. These values have to be settable per thread otherwise code in oen thread (eg calling setlocale) could unduly influence code running in a different thread.

_beginthread wraps your thread in code that performs the necessary allocation AND deallocation of these per thread data structures.

If you call CreateThread directly, the structures will probably be allocated as required, but without the wrapper, the runtime will never know when the thread exits and they will leak.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM