Further Thread Synchronization
Further Lock-based Thread Synchronization
Barriers
Copyright By Assignmentchef assignmentchef
Conditionvariables
A barrier is a synchronization point at which a certain number of threads must arrive before any participating thread can continue.
Participating threads call pthread_barrier_wait(). Participating threads block until the specified number of threads have called pthread_barrier_wait().
pthread_t thr[3];
pthread_barrier_t mybarrier;
void * tfunc (void * arg) { int i;
for (i=1; i
If >1 consumers wake up, only one will get the mutex and consume the data item.
Thereafter the next consumer might acquire the mutex.
Data item is consumed now!!
Re-check of condition necessary!
void *consumer(void *) {
pthread_mutex_lock(&data_mutex);
while( data_avail == 0 ) {
// sleep on condition variable: pthread_cond_wait(&data_cond, &data_mutex);
// woken up, execute critical section: Extract data from queue;
if (queue is empty)
data_avail = 0;
pthread_mutex_unlock(&data_mutex);
consume_data(); }
The producer-consumer example requires a second condition variable to signal the buffer empty condition to the producer.
This has been omitted here for brevity.
Example: 2 consumers blocking on condition
data_mutex
Owned by producer
Owned by producer
Owned by producer
Owned by consumer 1
Owned by consumer 1
Owned by consumer 2
data_avail
data_avail=1
cond_signal() unlock (data_mutex)
normal execution.
data_avail==1 ?
extract all data data_avail=0
unlock (data_mutex)
2 consumers are blocking on the waiting queue of the data_cond condition.
The producer signals data_cond, which moves both consumers to the mutex waiting queue.
The producer unlocks the mutex, consumer 1 acquires mutex and consumes data, resetting the data_avail flag.
Consumer 1 unlocks the mutex; Consumer 2 acquires the mutex. No more data available, so consumer 2 has to block once more on the condition variable. 15
data_avail==1 ? cond_wait()
Further Lock-based Thread Synchronizationu Barriersu
Condition variablesu
CS: assignmentchef QQ: 1823890830 Email: [email protected]
Reviews
There are no reviews yet.