Syncronizing Threads
int foo = 0; void foo_initializer() { if (foo == 0) foo = 1; /* This must only be done once. */ }Here is a possible execution sequence...
Thread 1 Thread 2 if (foo == 0) if (foo == 0) foo = 1; foo = 1;Both Thread 1 and Thread 2 set foo.
int pthread_mutex_init(pthread_mutex_t * mutex, pthread_mutexattr_t *attr);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int pthread_mutex_destroy(pthread_mutex_t * mutex);
int pthread_mutex_lock(pthread_mutex_t * mutex)
int pthread_mutex_trylock(pthread_mutex_t * mutex)
int pthread_mutex_unlock(pthread_mutex_t * mutex)
int foo = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void foo_initializer() { pthread_mutex_lock(&mutex); if (foo == 0) foo = 1; /* This must only be done once. */ pthread_mutex_unlock(&mutex); }