Example: One-time initialization in Pthread programs

This example shows a Pthread program that dynamically initializes an integer using the one-time initialization support.

Note: By using the code examples, you agree to the terms of the Code license and disclaimer information.
/*
Filename: ATEST20.QCSRC
The output of this example is as follows:
 Enter Testcase - LIBRARY/ATEST20
 Create/start threads
 Wait for the threads to complete, and release their resources
 Thread 00000000 00000007: Entered
 Thread 00000000 00000000: INITIALIZE RESOURCE
 Thread 00000000 00000007: The resource is 42
 Thread 00000000 00000006: Entered
 Thread 00000000 00000009: Entered
 Thread 00000000 00000008: Entered
 Thread 00000000 0000000a: Entered
 Thread 00000000 00000006: The resource is 42
 Thread 00000000 0000000a: The resource is 42
 Thread 00000000 00000009: The resource is 42
 Thread 00000000 00000008: The resource is 42
 Main completed
*/
#define _MULTI_THREADED
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>t
#include <unistd.h>
 
#define checkResults(string, val) {             \
 if (val) {                                     \
   printf("Failed with %d at %s", val, string); \
   exit(1);                                     \
 }                                              \
}
 
#define                 NUMTHREADS   5
pthread_once_t          oneTimeInit = PTHREAD_ONCE_INIT;
int                     initialized = 0;
int                     resource    = 0;
 
void initFunction(void)
{
   printf("Thread %.8x %.8x: INITIALIZE RESOURCE\n");
   resource = 42;
   /* Ensure that all initialization is complete and flushed */
   /* to storage before turning on this boolean flag         */
   /* Perhaps call a function or register an exception       */
   /* that causes an optimization boundary                   */
   initialized = 1;
}
 
void *theThread(void *parm)
{
   int   rc;
   printf("Thread %.8x %.8x: Entered\n", pthread_getthreadid_np());
   if (!initialized) {
      rc = pthread_once(&oneTimeInit, initFunction);
      checkResults("pthread_once()\n", rc);
   }
   printf("Thread %.8x %.8x: The resource is %d\n",
          pthread_getthreadid_np(), resource);
   return NULL;
}
 
int main(int argc, char **argv)
{
  pthread_t             thread[NUMTHREADS];
  int                   rc=0;
  int                   i;
 
  printf("Enter Testcase - %s\n", argv[0]);
 
  printf("Create/start threads\n");
  for (i=0; i <NUMTHREADS; ++i) {
  rc = pthread_create(&thread[i], NULL, theThread, NULL);
     checkResults("pthread_create()\n", rc);
  }
 
  printf("Wait for the threads to complete, and release their resources\n");
  for (i=0; i <NUMTHREADS; ++i) {
  rc = pthread_join(thread[i], NULL);
     checkResults("pthread_join()\n", rc);
  }
 
  printf("Main completed\n");
  return 0;
}