Hardware Reference
In-Depth Information
How does the condition variable help us? Consider the following steps:
1.
The mutex is locked (1).
2.
The wait is performed (3a). This causes the kernel to do the
following:
a.
Put the calling thread to sleep (put on a wait queue)
b.
Unlock the mutex that was locked in step 1
Unlocking of the mutex in step 2b is necessary so that another thread can do
something with the queue (hopefully, take an entry from the queue so that it is no longer
full). If the mutex remained locked, no thread would be able to move.
At some future point in time, another thread will do the following:
1.
Lock the mutex
2.
Find entries in the queue (it was currently full), and pull one
item out of it
3.
Unlock the mutex
4.
Signal the condition variable that the “waiter” is using, so that
it can wake up
The waiting thread then awakens:
1.
The kernel makes the “waiting” thread ready.
2.
The mutex is successfully relocked.
Once that thread awakens with the mutex locked, it can recheck the queue to see
whether there is room to queue an item. Notice that the thread is awakened only when it
has already reacquired the mutex lock . This is why condition variables are paired with a
mutex in their use.
pthread_cond_init(3)
Like any other object, a condition variable needs to be initialized:
int pthread_cond_init(
pthread_cond_t
cond,
const pthread_condattr_t
attr
);
cond : A pointer to the pthread_cond_t structure to be
initialized.
attr : A pointer to a cond variable attribute if one is provided,
or supply zero (or NULL ).
returns : Zero is returned if the call is successful; otherwise, an
error code is returned (not in errno ).
 
Search WWH ::




Custom Search