[fpc-pascal] Shared libraries and threadvars

Mark Morgan Lloyd markMLl.fpc-pascal at telemetry.co.uk
Tue Jun 26 17:14:57 CEST 2012


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.

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

-- 
Mark Morgan Lloyd
markMLl .AT. telemetry.co .DOT. uk

[Opinions above are the author's, not those of his employers or colleagues]



More information about the fpc-pascal mailing list