Use of global and static variables in shared libraries - Mailing list pgsql-hackers

From Don Walker
Subject Use of global and static variables in shared libraries
Date
Msg-id 000901c7f6e3$90036860$dbd849c6@donxp
Whole thread Raw
Responses Re: Use of global and static variables in shared libraries
List pgsql-hackers
I'm in the process of converting some C functions written for another system
into C functions in a shared library that will be used by PostgreSQL, The
key function will be the state transition function for a user-defined
aggregate. From what I've read in the documentation:

1. the state value should initially be allocated in  the "((AggState
*)fcinfo->context)->aggcontext" memory context.
2. this value will be passed to successive calls of the aggregate until it
completes and calls it's final function.

Since my state is fairly complex I intend to make my state value type text
to give myself a block of memory in which I can manage the various pointers
I need. I realize that I will need to be careful about alignment issues and
intend to store the state as a large struct in the data area of the text.

Q1 Is this approach for the state variable reasonable?

The existing C code that I've inherited makes heavy use of static and global
variables. I immediately assumed that for thread safety I'd need to roll any
of these variables that need to survive a function call into the state
variable struct and change any that were just for convenience instead of
parameters into parameters to my internal functions. I wanted to verify this
approach and have done fairly extensive searching on both the PostgreSQL
site and the Web in general. I didn't find any general guideline about not
using static and  global variables. I did find a reference in the FAQ,
http://www.postgresql.org/docs/faqs.FAQ_DEV.html#item1.14 that "threads are
not currently used in the backend code".

Q2 Is my assumption that I shouldn't be using static and global variables in
a shared library because they aren't safe under whatever task switching
mechanism the backend is using correct?



pgsql-hackers by date:

Previous
From: Darcy Buskermolen
Date:
Subject: Re: autovacuum launcher eating too much CPU
Next
From: Markus Schiltknecht
Date:
Subject: Re: terms for database replication: synchronous vs eager