pthread_self().
static int *foo
do...() {
if(foo == NULL) {
foo = malloc(10*sizeof(int));
}
}
The test foo == NULL
may not be atomic and that allows two threads
to potentially execute the same conditional body,
i.e. the allocation.
This happens if thread A performs the test,
determines it is true and immediately thread B becomes
active and performs the same test, yielding the same result.
Then both perform the allocation and at best
we have a dangling allocation that is nevery freed.
Worse things can of course happen.
There are serveral ways to solve this.
int foo() {
static int count = 0;
}
The latter may be handled in other ways - e.g. thread-specific
data may be appropriate.
do...() {
LOCK(fooLock);
if(foo == NULL) {
foo = malloc(10*sizeof(int));
}
UNLOCK(fooLock);
would do the trick.
There is an issue of dynamically allocating
the fooLock in a thread-safe manner,
thus requiring another lock!
pthread_once() and
a pthread_once_t variable
pthread_once(), will be
called
once and only once. The first thread that invokes
gets to enter the routine and the
others return immediately.
Any thread invoking the routine will block until the entire
routine has been executed that one time.
(I.e. there is an implicit barrier or rendezvous point).
Again this works for global variables rather than
static variables within routines since they must be
initialized with the routine.
Basically, I think that we can grab a C-grammar and lexer for our
favorite parser generator (ANTLR)
and build the rules in a reasonable simple application that modifies
the code inline to add the extra ``constant'' arguments - specifically
the evaluator - and identifies and makes suggestions about the global
and static variables. This could group these into
structs and offer to add these as arguments to routines,
create initialization routines that are protected via the
pthread_once() mechanism, etc. This is non-trivial, but
feasible. It would reduce the human error and be vaguely interesting
in its own right.