How to use multiple instances of the same lib

491 Views Asked by At

I have to extend a C program which controls a single drone (parrot AR Drone). The goal is to control a squadron of drones, but the API uses a huge amount of global variables (drone IP, ports, drone status...). How can I instanciate several times the library, without having "collision" between instances?

The only solution I've found is to modify the API (which is open source) to call fork() somewhere in the main() function, and I'd like to avoid this...

3

There are 3 best solutions below

0
On

I would recommend just wrapping the library in a service process. Then you can run one instance of the service process for each drone. Otherwise, fix the library to take a context parameter.

1
On

dlmopen can load one library multiple times. But it's limited to 15 times.
You can also create multiple copies of your library and load each of them.

1
On

Use macros to replace all of the global variables like this:

#define global1 ctx->global1
#define global2 ctx->global2
...

Then add a struct context *ctx argument to every function.

Alternatively, add _Thread_local (or __thread with old versions of gcc) to each global variable, then run each "instance" in its own thread so it naturally has its own copies of the globals available to it.