[Wolves] Re: Re-entrancy in C. AQ! RON! Anyone who codes in C!!!
Ron Wellsted
ron at wellsted.org.uk
Mon Oct 27 20:00:58 GMT 2003
On Monday 27 October 2003 10:36 am, bambam at opendildonics.org wrote:
> On Sun, 26 Oct 2003, Peter Oliver wrote:
> > On Sat, 25 Oct 2003 bambam at opendildonics.org wrote:
> > > Chatting to himself since yesterday. WHERE ARE YOU PETER
> > > OLIVER?!?!?
> >
> > If you really want to know, I was in Nottingham :-)
> >
> > Anyway, I'm afraid that I've already imparted all my knowledge on this
> > subject. Sorry.
>
> Can anyone else help? I think I understand it now, but it
> would help to have other's input.
Refering back to your original post:
> How do I make my C libraries reentrant?
For C the solution is to make all variables "auto" and avoid "static"
variables ie no global variables. This is because auto variables will be
automatically allocated storage space on the stack on each call to the
function ( at run-time), whereas a static will be allocated a fixed memory
location at link-time. Static strings are not included as they are not
variable.
> Presumably I change the API to accept a pointer to any
> objects which should be "instance" variables - so that you
> may "re-enter" the library anywhere. Correct?
This is very good practice for a lib function. This is where structures
become very useful as you can define a place to hold working storage
(instance variables). This is what happens with C++ constructors/
destructors. When you define the C++ class a structure is defined with all
the required class variables and a call made to malloc(sizeof(struct)) (then
the init function is called). Destroying an instance results in a call to
the destructor function then finally a free(struct).
> Also, does correct re-entrancy imply thread-safe? Surely if
> the code does not access any global variables within the
> library (are these "class" variables?) then threads using
> the library don't collide.
Just remember that declaring a variable (or a string etc) results in memory
being allocated.
> Were I writing this in Java I would easily be able to
> differenciate between them from the class definition, but
> I'm not sure of how the ideas pervade C.
I don't know java well enough to compare (I can eyeball java and follow what
is happening, but that's about it)
> How does static code relate to the whole thing? It seems as
> though if an object file within the shared library file
> declared a potentially global variable as static, only that
> part of the shared object can access it, but this whole idea
> still fucks up re-entrancy.
You are correct. Avoid statics variables for re-enterancy, unless you are
implementing a semaphore around a non re-enterant section of code.
I hope this has not made it more confusing.
--
Ron Wellsted
http://www.wellsted.org.uk
ron at wellsted.org.uk
N 52.567623, W 2.137621
More information about the Wolves
mailing list