Pthreads provides three synchronization mechanisms :
- Joins
- Mutual exclusions (“Mutex)
- Conditional variables
Synchronizing threads using join
pthread_join()is a blocking function
int pthread_join(
pthread_t thread_id, // ID of thread to "join"
void **value_pntr // address of function’s return value
);- Again, we’ll set
value_pntrtoNULL
int pthread_join(
pthread_t thread_id, // ID of thread to "join"
NULL
);Mutual exclusion in Pthread : mutex
- Syntax for declaration and initialization of a mutex is
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;- Creates a mutex ‘mutex1’ and initializes it with the default characteristics.
- Generally, mutexes are declared as global.
- Use of mutex for serializing access to a shared resource.
...
pthread_mutex_lock(&mutex1);
counter++;
pthread_mutex_unlock(&mutex1);
...- Thread access
counterserially one after another.
Conditional variables : syntax
- A conditional variable is a variable of type
pthread_cond_t.
pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER;- A thread goes to waiting state based on ‘condition to happen’ by:
pthread_cond_wait(&condition_cond, &condition_mutex);Function takes two arguments: the condition variable and a mutex variable associated with the condition variable.
pthread_cond_signal(&condition_cond);