Hardware Reference
In-Depth Information
Error
Description
EINVAL
The value specified by mutex does not refer to an initialized mutex
object.
EPERM
The current thread does not own the mutex.
A simple example of unlocking a mutex is provided here:
pthread_mutex_t mutex;
int rc;
...
rc = pthread_mutex_unlock(&mutex);
Condition Variables
Sometimes mutexes alone are not enough for efficient scheduling of CPU between
different threads. Mutexes and condition variables are often used together to facilitate
inter-thread communication. Some beginners might struggle with this concept, if they are
seeing it for the first time.
Why do we need condition variables when we have mutexes?
Consider what is necessary in building a software queue that can hold a maximum of
eight items. Before we can queue something, we need to first see if the queue is full. But
we cannot test that until we have the queue locked—otherwise, another thread could be
changing things under our own noses.
So we lock the queue but find that it is full. What do we do now? Do we simply
unlock and try again? This works but it wastes CPU resources. Wouldn't it be better if we
had some way of being alerted when the queue was no longer full?
The condition variable works in concert with a mutex and a “signal” (of sorts). In
pseudo code terms, a program trying to queue an item on a queue would perform the
following steps:
1.
Lock the mutex. We cannot examine anything in the queue
until we lock it.
2.
Check the queue's capacity. Can we place a new item in it?
If so:
a.
Place the new item in the queue.
b.
Unlock and exit.
3.
If the queue is full, the following steps are performed:
a.
Using a condition variable, “wait” on it, with the
associated mutex.
b.
When control returns from the wait, return to step 2.
 
 
Search WWH ::




Custom Search