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

8.5.3 Typical Uses of Condition Variables

8.5.3 Typical Uses of Condition Variables

Listing 8.1 illustrates the usage of the wait and the signal operations.

Listing 8.1: Pseudo code for wait and the signal operations.

Task 1
Lock mutex
 Examine shared resource
 While (shared resource is Busy)
  WAIT (condition variable)
 Mark shared resource as Busy
Unlock mutex
Task 2
Lock mutex
 Mark shared resource as Free
 SIGNAL (condition variable)
Unlock mutex

Task 1 on the left locks the guarding mutex as its first step. It then examines the state of the shared resource and finds that the resource is busy. It issues the wait operation to wait for the resource to become available, or free. The free condition must be created by task 2 on the right after it is done using the resource. To create the free condition, task 2 first locks the mutex; creates the condition by marking the resource as free, and finally, invokes the signal operation, which informs task 1 that the free condition is now present.

A signal on the condition variable is lost when nothing is waiting on it. Therefore, a task should always check for the presence of the desired condition before waiting on it. A task should also always check for the presence of the desired condition after a wakeup as a safeguard against improperly generated signals on the condition variable. This issue is the reason that the pseudo code includes a while loop to check for the presence of the desired condition. This example is shown in Figure 8.15.


Figure 8.15: Execution sequence of wait and signal operations.

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


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