Take the 2-minute tour ×

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...

share|improve this question
If the library is open source, why not modify the library to remove the global variables instead? –  Joachim Pileborg Feb 6 '12 at 10:50
@JoachimPileborg, this is easy to say. And for very simple, code, easy to do. –  ugoren Feb 6 '12 at 12:57
@ugoren If an answer has an easy workaround, then that might be the way to go, but if no easy workaround is possible, then a "proper" solution might be better. And it will probably be better for other users of the library if the maintainer gets a patch. –  Joachim Pileborg Feb 6 '12 at 13:16
@JoachimPileborg, The library's maintainer is one thing, the user is another. If you maintain a library, you should make it thread-safe. If you use somebody else's library, and he wouldn't make it thread-safe, then doing massive changes in code you don't know isn't normally an option. –  ugoren Feb 6 '12 at 15:22
add comment

3 Answers

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.

share|improve this answer
add comment

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.

share|improve this answer
I used this 'copy dynamic library' approach when I encountered the same problem. Quite ugly in my opinion, but it works well. –  Alexandre Hamez Feb 6 '12 at 12:34
This is really really ugly and not a good idea.. –  R.. Feb 6 '12 at 14:40
add comment

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.

share|improve this answer
The library itself is already mutltithreaded (thread functions are stored in global arrays...). Of course, the global variables are defined and used in multiple files, which is why I don't want to modify this API: too risky, and requires too much work. –  MouleMan Feb 6 '12 at 20:11
add comment

Your Answer


