[Return to Bookshelf] [Contents] [Previous Section] [Next Section] [Index] [Help]


pthread_once

Calls an initialization routine that can be executed by a single thread, once.

Syntax

pthread_once(
             once_control,
             init_routine );
 


Argument Data Type Access

once_control opaque pthread_once_t modify init_routine procedure read


C Binding

#include 

int pthread_once ( pthread_once_t *once_control, void (*init_routine) (void));

Arguments

once_control
Address of a record that defines the one-time initialization code. Each one-time initialization routine must have its own unique pthread_once_t record.
init_routine
Address of a procedure that performs the initialization. This routine is called only once, regardless of the number of times it and its associated once_control are passed to pthread_ once.

Description

The first call to this routine by any thread in a process with a given once_control will call the init_routine with no arguments. Subsequent calls to pthread_once with the same once_control will not call the init_routine. On return from pthread_once, it is guaranteed that the initialization routine has completed.

For example, a mutex or a per-thread context key must be created exactly once. Calling pthread_once ensures that the initialization is serialized across multiple threads. Other threads that reach the same point in the code would be delayed until the first thread is finished.

The pthread_once_t variable must be statically initialized using the PTHREAD_ONCE_INIT macro or by zeroing out the entire structure.


Note
If you specify an init_ routine that directly or indirectly results in a recursive call to pthread_once specifying the same init_block argument, the recursive call may result in a deadlock.

The PTHREAD_ONCE_INIT macro, defined in the header file, must be used to initialize a once_control record. A once_control record must be declared as follows:

 pthread_once_t  once_control = PTHREAD_ONCE_INIT;

Note that it is often easier to simply lock a statically initialized mutex, check a control flag, and perform necessary initialization (in-line) rather than using pthread_once. For example, code an init routine beginning with the following basic logic:

  init()
  {
   static pthread_mutex_t    mutex = PTHREAD_MUTEX_INIT;
   static int                flag = FALSE;

   pthread_mutex_lock(&mutex);
   if(!flag)
     {
      flag = TRUE;
      /* initialize code */
     }
   pthread_mutex_unlock(&mutex);
  }

Return Values

If an error occurs, this routine returns an integer indicating the type of error. Possible return values are as follows:
Return        Description

0 Successful completion. [EINVAL] Invalid argument.




[Return to Bookshelf] [Contents] [Previous Section] [Next Section] [Index] [Help]