How to use an old single-threaded C++ library in a multithreaded environment

1.6k views Asked by At

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?

2

There are 2 answers

7
Shamim Hafiz - MSFT On BEST ANSWER

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.

1
David Heffernan On

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.