Книга: Real-Time Concepts for Embedded Systems

15.2.3 Implementing Barriers

15.2.3 Implementing Barriers

Barrier synchronization is used for activity synchronization. Listing 15.1 shows how to implement a barrier-synchronization mechanism using a mutex and a condition variable.

Listing 15.1: Pseudo code for barrier synchronization.

typedef struct {
 mutex_t br_lock; /* guarding mutex */
 cond_t br_cond; /* condition variable */
 int br_count; /* num of tasks at the barrier */
 int br_n_threads; /* num of tasks participating in the barrier synchronization */
} barrier_t;
barrier(barrier_t *br) {
 mutex_lock(&br-›br_lock);
 br-›br_count++;
 if (br-›br_count ‹ br-›br_n_threads) cond_wait(&br-›br_cond,&br-›br_lock);
 else {
  br-›br_count = 0;
  cond_broadcast(&br-›br_cond);
 }
 mutex_unlock(&br-›br_lock);
}

Each participating task invokes the function barrier for barrier synchronization. The guarding mutex for br_count and br_n_threads is acquired on line #2. The number of waiting tasks at the barrier is updated on line #3. Line #4 checks to see if all of the participating tasks have reached the barrier.

If more tasks are to arrive, the caller waits at the barrier (the blocking wait on the condition variable at line #5). If the caller is the last task of the group to enter the barrier, this task resets the barrier on line #6 and notifies all other tasks that the barrier synchronization is complete. Broadcasting on the condition variable on line #7 completes the barrier synchronization.

Оглавление книги


Генерация: 1.108. Запросов К БД/Cache: 3 / 1
поделиться
Вверх Вниз