How does a shared library work?

janne jan.moren at
Wed Oct 26 08:49:40 UTC 2005

ons 2005-10-26 klockan 10:18 +0200 skrev Tshepang Lekhonkhobe:
> Hello,
> I wanted to avoid some searching headache by asking this question here:
> I hear that the advantage of shared libraries is that there's only one
> copy of that library in memory and I assume that the library is loaded
> in memory only the first moment that a dependant package is run. But
> who's reponsible for making sure whose turn it is to use that library
> in case of several dependant packages requiring its use? Is it the
> kernel?

Neither. When you write something to be used as a shared library, it
needs to be written to be "reentrant". That means the library must be
able to have more than one process use it - even use the same exact code
- at the same time. That is not as big a headache as it sounds.

Remember that the code itself is never actually changed; it is in effect
a fixed text run by the processes (the same is true of just about any
code in fact). The problem is variables that do change, but that is
neatly solved by the memory controller:

Every process has its own mapped memory. This memory is divided into
text segments (the actual code) and data segments (room for variables,
stack and other data that changes as you run the application). When you
use the shared library, its code is mapped into the processes memory.
Note that it's not copied - there's still only one "real" copy - but the
memory controller effectively makes it seem it's part of the rest of the
program code. 

Now, the library too has text and data areas. But while the text (the
code) is mapped into all the processes that use it (so there's only one
copy, used by everybody), it's _data_ segment is different for each
process, and is a part of each process' data segment. So as the system
skips from one process to the next, what data (variables and so on) the
library sees changes along with the process that uses it. 

So for "normal" code there really is no problem. Anything that could
collide between processes won't, since they each have their own private
copy of the data that differs. The problem only comes with external
resources that aren't shareable.

Tel. (Japan) 090-3622 8920            Dr. Jan Morén (mr)
Sweden: +46-31 360 7723               Dept. of Cognitive Science    Lund, Sweden

More information about the ubuntu-users mailing list