Kiril Kirov
Kiril Kirov

Reputation: 38173

Dynamic linking, memory usage and concurrency

When an executable links with a static library, the executable contains only the necessary library parts, that are used in the code, right?

But I'm missing the part with - how the shared objects (the dynamic linked libraries) are used exactly?

As far as I know, they are not included in the executable, they are dynamically loaded using dlopen and this is done directly by the linker, right?

In this case, where's this library located in the memory? I mean, there are posts here, explaining that the dynamic libraries could reduce the memory usage, but how exactly? And if a dynamic library is somehow loaded into a shared memory (for several processes), how the kernel handles the concurrency in this case?

I realize this is something probably fundamental and sorry if this is a duplicate, I couldn't find such.
I am aware of Static linking vs dynamic linking and what I ask is a bit different.

Upvotes: 3

Views: 1899

Answers (2)

Mats Petersson
Mats Petersson

Reputation: 129454

The shared library is indeed loaded into memory that is shared between all "users" (all applications using the same library).

This is essentially done by reference-counting, so for each new user of the library, the reference is counted up. When an application exits, the reference count is counted down. If it gets to zero, the library is no longer needed, and will be removed from memory (quite possibly only when "memory is needed for something else", rather than "immediately"). The reference counting is done "atomically" by the kernel, so there is no conflict of concurrency.

Note that it's only the CODE in the shared library that is actually shared. Any data sections will be private per process.

Upvotes: 8

Tobias Langner
Tobias Langner

Reputation: 10828

the dynamic library is loaded only once for all the processes that are using them. The memory of the dynamic library is then mapped into the process adress space by the operating system. This way, it consumes its required memory only once. With static linking, all executables include the statically linked code. When the executable is loaded, the statically linked code is loaded as well. This means, a function that is included in 10 executables resides 10 times in memory.

Upvotes: 0

Related Questions