Miscellaneous¶
One-Time Initialization (1)¶
Where’s the bug?
static X *global;
void use_global()
{
if (global == NULL)
global = new X;
// ... use global ...
}
One-Time Initialization (2)¶
static pthread_once_t global_once = PTHREAD_ONCE_INIT;
static X *global;
static void init_global() { global = new X; }
void use_global()
{
pthread_once(&global_once, init_global);
// ... use global ...
}
One-Time Initialization (3)¶
int pthread_once(pthread_once_t *once_control,
void (*init_routine)(void));
pthread_once_t once_control = PTHREAD_ONCE_INIT;
Thread Specific Data, Thread Local Storage¶
POSIX thread API for Thread Specific Data - per thread global variables ⟶ man 3 pthread_key_create (including example).
Non-portable alternative:
static __thread X* global;