[fpc-pascal] Shared libraries and threadvars

Sven Barth pascaldragon at googlemail.com
Tue Jun 26 15:26:33 CEST 2012


Am 26.06.2012 14:02 schrieb "Mark Morgan Lloyd" <
markMLl.fpc-pascal at telemetry.co.uk>:
>
> 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)?

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.

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.

Regards,
Sven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20120626/1757523e/attachment.html>


More information about the fpc-pascal mailing list