Use of global and static variables in shared libraries

From: "Don Walker" <don(dot)walker(at)versaterm(dot)com>
To: <pgsql-hackers(at)postgresql(dot)org>
Subject: Use of global and static variables in shared libraries
Date: 2007-09-14 15:26:03
Message-ID: 000901c7f6e3$90036860$dbd849c6@donxp
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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?

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Darcy Buskermolen 2007-09-14 15:44:09 Re: autovacuum launcher eating too much CPU
Previous Message Bruce Momjian 2007-09-14 15:07:31 Re: pg_dump and insert multi-rows option