Removing Global Variables for Rentrance and Thread-safety.

In order to let two or more threads run simultaneously with predictable outcomes, we must arrange that

Values Initialized Just Once

There are variables that are initialized in a block of code that is executed just once. For example,
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.

  • Initialize the values before a second thread is ever created.
    This avoids the synchronization issue. However, it results in increased startup time, allocation of values that may never be used rather than allocation on demand and finally does not work for static variables within methods:
          int foo() {
           static int count = 0;
          }
          
    The latter may be handled in other ways - e.g. thread-specific data may be appropriate.
  • We can use an explicit lock around the entire test.
    For example, assuming the LOCK and UNLOCK mechanism
          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!
  • Use pthread_once() and a pthread_once_t variable
    Basically, this arranges that a particular routine, registered in the call to 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.

  • Duncan Temple Lang <duncan@research.bell-labs.com>
    Last modified: Thu May 27 13:11:06 EDT 1999