TLS回调函数无效

Thread Local Storage

关联问题:Debug下tls回调正常,release下却没有执行、Thread Local Storage Exception Handler error

链接:c++ - Exception Handler error code in Thread Local Storage - Stack Overflow

          Thread Local Storage Exception Handler error - Programming and Coding - Tuts 4 You

原因:Debug下Runtime Library 默认为动态链接 Multi-threaded Debug Dll(/MDd)    Release下常常设置成静态链接Multi-threaded (/MT)

I noticed the problem occurs when Runtime Library set to /MT or /MTd.


Like I said, the way you are linking is preventing it from working properly. The CRT is loaded after TLS callbacks occur when you statically link to it. Meaning the calls and data you are trying to use are not ready yet. When you link dynamically to it, things are loaded as they are requested so you can use them anywhere. If you want to keep things portable, you need to avoid using CRT specific calls (for example in your case wprintf) within the TLS callback. You shouldn't be doing things like that in a TLS callback anyway, it is used to initialize data.


当静态链接时,在 TLS 回调发生后,CRT 会加载。这意味着尝试调用的函数和数据尚未准备好。当动态链接到它时,当需要时,东西会被加载,以便可以在任何地方使用它们。如果你想要保持便携性,则需要避免在 TLS 回调中使用 CRT 特定函数(CRT函数,例如, wprintf )。无论如何, 你不应该在 Tls 回调中做这样的事情, 它被用来初始化数据。‎

 解决方案:Runtime Library选择动态链接(/MD    /MDd)                或在tls中不使用CRT(C Runtime)函数

推荐阅读:

《程序员的自我修养——链接装载与库》

Thread Local Storage (TLS) | Microsoft Docs

C Runtime Error R6016 | Microsoft Docs

原文地址:https://www.cnblogs.com/DirWang/p/15251350.html