简体   繁体   中英

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.

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.

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?

If the DLL contains static resources, then those would be shared among all instances created.

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.

The sharing of static resources between all threads attached to a single DLL within a process conspires against you here.

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.

The way to achieve this is, for each thread, copy the DLL to a temporary file and load from there with LoadLibrary . You have to use explicit linking ( GetProcAddress ) rather than lib files but that's really the only way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM