c++, multiple instances of a dll, singleton - c++

I have got a DLL in which a singleton is defined.
I have got an app which can load multiple instances of this DLL.
The DLL needs a singleton instance per DLL instance, otherwise it will crash.
I observed that there was only one singleton instance for multiple DLL instances. Why? How can I resolved it (if possible, without refactoring the singleton into something else)?
Thanks for any help.

You mentioned that you have multiple instances inside your app, which implies that they all live inside the same process.
Singletons like any other static member are limited to one per application regardless of whether they belong to an object loaded from a DLL etc.

No way without refactoring your code. A DLL is "loaded" into the process space. Any static member defined in there is static for the process (a loaded DLL doesn't have its own memory).
You'll have to write a non-standard "singleton" to get multiple objects.

And if you don't have the sources to the dll, then you must load it in different processes, one "singleton" per process. These could be simple child-processes to your main process that just handle the dll communication part.
Then of course, you must come with some communication scheme between your main process and your child processes, which will depend on how much you are using the dll. Is it just a couple of calls with a lot of data? Or a lot of different calls that differ from run to run?
Generally if you are using the dll to make more than a couple of simple calls it's probably easier to refactor your own code.

Related

How to create more than one instance with own copy of global variables

I have two projects:
Embedded one, written in C++, which uses a lot of static/global variables.
Second one, running on PC and using the same source codes as embedded one uses.
It works very well.
But now second project should run more than one instances of embedded project. Furthermore each instance should have its own copy of static/global variables, and I should be able to interact with each instance in one program scope. I don't know how to do this with all that static/global variables.
Is there any simple way to solve my problem?
There are several ways you can solve this:
Spawn multiple processes (each with their own set of globals) and setup channels of communication between them and the main program.
Get rid of the global variables. The easiest way to do this would be to dump them all in a class (as non-static members) and use instances of that class to access each set of variables.
Either way, it's not a small problem to solve if you have a large number of globals.
Run two separate processes and use some form of IPC to communicate between the the processes. In Windows IPC mechanisms available include:
Clipboard
COM
Data Copy
DDE
File Mapping
Mailslots
Pipes
RPC
Windows Sockets
See here for details of each of these. Similar mechanisms are available in other operating systems.
A perhaps simpler alternative is to run each instance in a separate thread and place the globals in thread local storage.
In all cases however, you should avoid nit just "a lot" but any global variables. It is generally indicative of poor design. See this article for why globals are bad, and ways to avoid them.
As the other answers state the best solution is to get rid of the globals, but I understand that this is not always feasible.
I ran into the exact same problem with our code base.
The solution I used was to build each instance as a separate DLL.
Then load I loaded each DLL with LoadLibrary() at runtime.
In this way you can get everything to run in a single process and have multiple version of the same globals and singletons.
And then you don't need to use any IPC but can pass data between the instances with a simple function call. It also makes the debugging easier, because you can see everything in one debugger.
NOTE: I made it on Windows, but I assume the something similar is possible on Unix.

How to detect DLL is not used by Any Application

I have a DLL which invokes an application running underneath. This DLL is loaded by several other applications/processes simultaneously.
So, Basically Architecture is:
My Problem is if Application(s) using DLL is crashed, I want to execute an exit sequence in my Base Application and Exit it.
How can I detect that this DLL is no longer used by any application?
Is there any thing like Load Count of DLL which I can keep track of?
Another glitch is I may have to monitor this via a C# application but that is a further thing.
If you can shell an external program to do the check, you can use this:
http://technet.microsoft.com/en-us/sysinternals/bb896656
Your image is not a good model for what really happens in Windows. Every process gets its own copy of the DLL. The code inside the DLL is shared in RAM but not its data. There are ways to share data as well but that's not otherwise common, a memory mapped file is the far more typical approach.
Windows doesn't give cheap way to find out if a DLL is loaded into a process. There is no notification mechanism either. Whatever you do, it has to start with the processes first. That works in C# too, you could use the Process.Modules property.
Just keeping track of the processes you know that load the DLL is probably sufficient, when the process no longer runs then you can safely assume it doesn't have the DLL loaded anymore either. Use the Process.Exited event or use WMI as shown in this answer.
You could host the DLL in the Base Application either and implement your own ref count using shared sections, easy, and often used. As already mentioned, one possibility would be to implemented your ref counting inside your DLL entry point and detect DLL_PROCESS_DETACH, DLL_THREAD_DETACH, DLL_PROCESS_DETACH, etc according to you specifications.

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.

Scenario: Global variables in DLL which is used by Multi-threaded Application

Few months back, I had come across this interesting scenario asked by a guy (on orkut). Though, I've come up with a "non-portable" solution to this problem (have tested it with small code), but still would like to know what you guys have to say and suggest.
Suppose, I created a DLL, exporting some functionalities, written in C++, for single threaded client. This DLL declares lots of global variables, some maybe const variables (read-only) and others are modifiable.
Anyway, later things changed and now I want the same DLL to work with multi-threaded application (without modifying the DLL); that means, several threads access the functions and global variables from the DLL, and modify them.. and so on. All these may cause global variables to hold inconsistent values.
So the question is,
Can we do something in the client code to prevent multi-access of the DLL, and at the same time, ensuring that each thread runs in it's own context (meaning, when it gets access to the DLL, the DLL's global values are same as it was before)?
Sure, you can always create a wrapper-layer handling multi-threading specific tasks such as locking. You could even do so in a second DLL that links with the original one, and then have the final project link with that new DLL.
Be aware that no matter how you implement it, this won't be an easy task. You have to know exactly which thread is able to modify which value at what time, who is able to read what and when etc. unless you want to run into problems like deadlocks or race conditions.
If you're solution allows it, it's often best to assign a single thread to modify any data, and have all others just read and never write, as concurrent reading access is always easier to implement than concurrent writing access (Boost provides all basic functionality to do so, for example shared_mutex).
Can we do something in the client code to prevent multi-access of the DLL, and at the same time, ensuring that each thread runs in it's own context (meaning, when it gets access to the DLL, the DLL's global values are same as it was before)?
This is the hard part. I think the only way top do this would be to create a wrapper around teh existing DLL. When it is called, it would restore the state (global variables) for the current thread, and save them when the call to the DLL returns. You would need to know all of the state variables in the DLL, and be able to read/write them.
If performance is not an issue, a single lock for the entire DLL would suffice, and be the easiest to implement correctly. That would ensure that only one thread was accessing (reading or writing) the DLL at one time.

Are Multiple singleton instances possible in a shared DLL?

I am going to develop a DLL for an MFC Application, and suppose I have a singleton class in this DLL with some synchronization mechanism. And this DLL is used by other processes, namely EXEs. The question is: is this singleton created only once for all sharing processes or every process has its own singleton?
And How can I solve this multiple singleton problem?
I suppose you are talking about Windows. In that case every process has its own singleton. You could place it in shared memory and use named synchronization primitives to share singleton between processes.
If based on the singleton pattern, it'll end up being one singleton per process. Note that if you run multiple threads within that process there will still only be one singleton.
It depends. By default, all data in a DLL is non-shared and all code is shared. But by using #pragma section ("SharedSingleton", read, write, shared) you create a data section named "SharedSingleton", which is shared across all users of the DLL.
Note that this does introduce security risks! Another troublesome issue you might encounter is the initialization of the singleton; C++ doesn't really understand the concept of shared sections.