[英]How to use an old single-threaded C++ library in a multithreaded environment
I have an old C++ library which has been designed for use in single-threaded environmens. 我有一个旧的C ++库,专为在单线程环境中使用而设计。
The library exposes the interfaces for initialization, which change the internal data structures of the library, and usage, which only reads data and makes calculations. 该库公开了用于初始化的接口,这些接口改变了库的内部数据结构,以及用法,它只读取数据并进行计算。
My objective is to use this library in a Windows multithreaded application, with different threads calling instances of the dll initialized with different data. 我的目标是在Windows多线程应用程序中使用此库,其中不同的线程调用使用不同数据初始化的dll实例。
Assuming that rewriting the dll to allow multithreading would be prohibitive, is there some way to let multiple instances of a DLL exist in the same process, with separate memory spaces, or to obtain a similar result by other means? 假设重写dll以允许多线程将是禁止的,是否有一些方法让DLL的多个实例存在于同一进程中,具有单独的内存空间,或通过其他方式获得类似的结果?
If the DLL contains static resources, then those would be shared among all instances created. 如果DLL包含静态资源,那么这些资源将在创建的所有实例之间共享。
One possible way would be to create a single instance and restrict access to it using some kind of lock mechanism. 一种可能的方法是创建单个实例并使用某种锁机制限制对它的访问。 This may reduce performance depending on usage, but without modifying internal structure of DLL, it may be difficult to work with multiple instance.
这可能会降低性能,具体取决于使用情况,但是如果不修改DLL的内部结构,则可能难以使用多个实例。
The sharing of static resources between all threads attached to a single DLL within a process conspires against you here. 在进程中连接到单个DLL的所有线程之间共享静态资源会在这里与您发生冲突。
However, there is a trick to achieve this. 但是,有一个技巧可以实现这一目标。 So long as DLLs have different names, then the system regards them as being different and so separate instances of code and data are created.
只要DLL具有不同的名称,系统就会将它们视为不同,因此会创建单独的代码和数据实例。
The way to achieve this is, for each thread, copy the DLL to a temporary file and load from there with LoadLibrary
. 实现此目的的方法是,对于每个线程,将DLL复制到临时文件并使用
LoadLibrary
从那里加载。 You have to use explicit linking ( GetProcAddress
) rather than lib files but that's really the only way. 你必须使用显式链接(
GetProcAddress
)而不是lib文件,但这确实是唯一的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.