[fpc-pascal] Shared libraries and threadvars

Sven Barth pascaldragon at googlemail.com
Tue Jun 26 19:53:11 CEST 2012

Am 26.06.2012 17:15 schrieb "Mark Morgan Lloyd" <
markMLl.fpc-pascal at telemetry.co.uk>:
> Mark Morgan Lloyd wrote:
>>> I'm currently tinkering with shared libraries, using cmem, mainly on
Linux. In one case the main-program code is multithreaded, but so far I'm
not moving data between threads inside the library.
>>> Am I correct in believing that unit-level variables in a shared library
might end up being shared between multiple instances of the library, or are
they guaranteed to be distinct?
>>> If my belief is correct, I presume that I could get around this by
using threadvars. But in this case, how would I best implement a variable
that I wanted to be common across related threads (e.g. to track the number
of a particular object being allocated/deallocated), but distinct across
program invocations (i.e. two programs using the same shared library
wouldn't clash)?
>>> The discussion of libraries in ch16 of the Language reference guide is
rather quiet on the semantics.
> >
> > A programs memory always belongs to itself (exceptions through mmap or
> > kernel related thing excluded) and libraries are loaded into the
> > program's memory. Their code sections might only exist once if the OS
> > detects that it had already loaded the library somewhere, but it's
> > data sections and also the memory it allocates during its lifetime
> > belong to the program's memory.
> Thanks Sven. So to summarise: code might be shared, but this generally
won't be relevant since it should be read-only. Data- local or global-
won't be shared.

Correct. Shared code sections shouldn't matter normally.

> > This means for you: normal global variables in your library are not
> > shared with other "instances" of this library (note: if a program
> > loads library A and B and library A also loads B then there is only
> > one "instance" of the library and its data). They are shared by all
> > threads that use this library though. Having variables shared between
> > different "instances" of a library is a different topic altogether.
> OK, so to emphasise that: library B's data will be common, irrespective
of the location of the calling routine. Does this apply if the load is
being done at runtime, i.e. the program is using dl (or whatever) to load A
and B, and A also uses dl to load B?

It does not matter whether the library is loaded at program start or at
runtime. It's always the same mechanism with the exception that in the
first case your main function has not yet been called (which normally
doesn't matter either).

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20120626/0520e345/attachment.html>

More information about the fpc-pascal mailing list