关于Windows API和C/C的问题++运行时库函数
当我为Windows平台编写C/C++代码时,我通常会根据需要使用Windows API。但是说到多线程,我从<<<< 通过 C/C++ 运行 Windows >
CreateThread函数是 创建线程的 Windows 函数。 但是,如果您正在编写 C/C++ 代码,你不应该调用 创建线程。相反,你应该使用 Microsoft C++ 运行时库 函数_beginthreadex。如果你不这样做 使用微软的C++编译器,你的 编译器供应商将有自己的 CrateThread 的替代方案。任何 这个替代方案是,您必须使用它。
AFAIK,特定平台的语言运行时库是通过该平台的 API 实现的。我认为完全可以从我的 C/C++ 代码中调用 CreateThread() 。我确实做到了。但我只是不明白为什么要遵循上述规则。
非常感谢您的见解。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当然可以直接使用Windows API的
CreateThread
。但这使得运行时库不知道新线程。
对于运行时库中的多线程支持(并且包括依赖于静态存储的函数,例如我想它包括
strtok
),您需要让运行时库了解情况,不仅是了解情况,而且部分负责,例如未能分配线程所需的任何资源,会导致线程创建失败。干杯&呵呵,
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, e.g. I imagine it includes
strtok
) you need to keep the runtime library informed, and not only informed, but partially in charge so that e.g. failure to allocate whatever resources it needs for a thread, results in thread creation failure.Cheers & hth.,
c 运行时有许多保存事物的状态变量,例如当前的语言环境。这些值必须可以按线程设置,否则某个线程中的代码(例如调用 setlocale)可能会不适当地影响在不同线程中运行的代码。
_beginthread 将线程包装在代码中,该代码对每个线程数据结构执行必要的分配和释放。
如果直接调用 CreateThread,结构可能会根据需要分配,但如果没有包装器,运行时将永远不会知道线程何时退出,并且它们会泄漏。
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 (e.g. 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.