LoadLibrary 静态/全局和线程
假设我有一个具有以下静态/全局的 DLL:
ClassA Object;
除了 ClassA 的实现之外,它还包含一个“常规”ClassB,如果尚未构造 ClassA,则它将无法正常工作(这就是我创建 ClassA 的原因)是静态/全局)。
在Windows中,我相信DLL加载器会在调用ClassB的构造函数时加载这个DLL,对吗?此时将构建ClassA,然后构建ClassB。如果第二个线程出现并构造 ClassB,则 ClassA 将不会被构造,因为它已经被构造了。
现在,我的问题是——如果 ClassB 由两个线程同时构造怎么办?于是线程1就会开始构造ClassA。线程2会等到ClassA完全构造完成之后才执行ClassB的构造函数吗?
换句话说,LoadLibrary() 是否使用 CriticalSection 来确保 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
DllMain
由 Windows 加载程序调用,同时持有称为“加载程序锁”的内部关键部分,因此您的静态构造函数将在DLL_PROCESS_ATTACH
事件期间被调用,该事件仅发生一次,当你的 DLL 第一次加载时。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 theDLL_PROCESS_ATTACH
event, which only occurs once, when your DLL is first loaded.查看DllMain的文档;我相信它谈论了加载程序锁定和初始化顺序。
Look at the documentation for DllMain; I believe it talks about the loader lock and initialization order.
DLL 不像 EXE 那样初始化,因为它们由多个进程共享。您实际上需要的是一个单例对象,它是其他对象的一次性工厂。
注意,我假设这里的“ClassA”和“ClassB”是指这些类的实例...
例如,您可以有类似的东西
第一次调用这些函数时,这些函数将确保您的 ClassA 和 ClassB 的全局实例B 级结构正确。
DLL's are not initialized like EXE's since they are shared by multiple processes. What you need is effectively a singleton object that is a one time factory for your other objects.
Note, I'm assuming here by "ClassA" and "ClassB" you mean instances of those classes...
For example you could have a someting like
The first time these are called, these functions would ensure that your global instances of ClassA and ClassB were properly constructed.