![]() |
![]() |
| ||||
Initializing Condition VariablesDeclare a condition variable (type kcondvar_t) for each condition. Usually, this is done in the driver's soft-state structure. Use cv_init(9F) to initialize each one. Similar to mutexes, condition variables are usually initialized at attach(9E) time. For example:
For a more complete example of condition variable initialization see Chapter 5, Driver Autoconfiguration. Waiting for the ConditionTo use condition variables, follow these steps in the code path waiting for the condition:
Signaling the ConditionFollow these steps in the code path signaling the condition:
Example 3-1 uses a busy flag along with mutex and condition variables to force the read(9E) routine to wait until the device is no longer busy before starting a transfer. Example 3-1 Using Mutexes and Condition Variables
cv_wait() and cv_timedwait() FunctionsIf a thread blocks on a condition with cv_wait(9F), and that condition does not occur, it can wait forever. For that reason, it is often preferable to use cv_timedwait(9F), which depends upon another thread to perform a wakeup. cv_timedwait(9F) takes an absolute wait time as an argument and returns -1 if the time is reached and the event has not occurred. It returns a positive value if the condition is met. cv_timedwait(9F) requires an absolute wait time expressed in clock ticks since the system was last rebooted. This can be determined by retrieving the current value with ddi_get_lbolt(9F). The driver usually has a maximum number of seconds or microseconds to wait, so this value is converted to clock ticks with drv_usectohz(9F) and added to the value from ddi_get_lbolt(9F). Example 3-2 shows how to use cv_timedwait(9F) to wait up to five seconds to access the device before returning EIO to the caller. Example 3-2 Using cv_timedwait()
Although device driver writers generally find it preferable to use cv_timedwait(9F) over cv_wait(9F), there are situations in which cv_wait(9F) is a better choice. For example, cv_wait(9F) would be better when a driver is waiting on:
cv_wait_sig() FunctionThere is always the possibility that either the driver accidentally waits for a condition that will never occur or that the condition will not happen for a long time. In either case, the user can abort the thread by sending it a signal. Whether the signal causes the driver to wake up depends upon the driver. cv_wait_sig(9F) allows a signal to unblock the thread. This enables the user to break out of potentially long waits by sending a signal to the thread with kill(1) or by typing the interrupt character. cv_wait_sig(9F) returns zero if it is returning because of a signal, or nonzero if the condition occurred. Example 3-3 shows how to use cv_wait_sig(9F) to allow a signal to unblock the thread. Example 3-3 Using cv_wait_sig()
| ||||
| ||||