LoadLibrary静态/全局和线程 [英] LoadLibrary Static/Globals and Threads

查看:245
本文介绍了LoadLibrary静态/全局和线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个具有以下静态/全局的DLL:

  ClassA Object; 

随着ClassA的实现,它还包含一个常规ClassB,无法正常工作如果ClassA尚未构建(这就是为什么我使ClassA是静态/全局的)。



在Windows中,我相信DLL加载器将加载DLL上调用ClassB的构造函数,是否正确?在这一点上,ClassA将被构建,然后ClassB的构建将会跟随。如果第二个线程来到并构造ClassB,ClassA将不会被构造为已经被构造。



现在,我的问题是 - 如果同时构建了ClassB通过两个线程。所以线程1将开始构建ClassA。在执行ClassB的构造函数之前,Thread 2会等待ClassA完全构造?



换句话说,LoadLibrary()是否使用CriticalSection来确保DLL的静态的线程安全初始化/全局?我的预感是'是',但我似乎找不到任何文字说出一种或另一种方式。

解决方案

code> DllMain 被Windows加载程序调用,同时持有称为加载程序锁定的内部关键部分,因此您的静态构造函数将在 DLL_PROCESS_ATTACH 事件,它只发生一次,当你的DLL首次加载。


Say I have a DLL that has the following static/global:

ClassA Object;

Along with the implementation of ClassA, it also contains a 'regular' ClassB, which will not work properly if ClassA has not been constructed yet (which is why I've made ClassA is a static/global).

In Windows, I believe that the DLL loader will load this DLL on the call to ClassB's constructor, correct? At this point, ClassA will be constructed and then ClassB's construction will follow. If a second thread comes along and constructs ClassB, ClassA will not be constructed as it has already been constructed.

Now, my question is -- what if ClassB is constructed simultaneously by two threads. So Thread 1 will start to construct ClassA. Will Thread 2 wait until ClassA is completely constructed before executing ClassB's constructor?

In other words, does LoadLibrary() use a CriticalSection to ensure thread-safe initialization of a DLL's static/globals? My hunch is 'yes', but I can't seem to find any documentation saying one way or the other.

解决方案

DllMain is called by the Windows loader while holding an internal critical section known as the "loader lock," so your static constructors will be called during the DLL_PROCESS_ATTACH event, which only occurs once, when your DLL is first loaded.

这篇关于LoadLibrary静态/全局和线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆