CS360 Final -- December 10, 2002
Answers to Question 3
- pthread_mutex_lock(mutex) works on a data structure called a mutex as follows.
When the mutex is initialized, it is unlocked. When a thread calls
pthread_mutex_lock(), if the mutex is unlocked, then it becomes locked, and
pthread_mutex_lock() returns. If the mutex is locked, then
pthread_mutex_lock() blocks until it is unlocked, and until
pthread_mutex_lock() acquires the lock. Only one thread may acquire the lock
at any one time.
- pthread_cond_wait(cond, mutex)
works on two data structures -- a lock and a condition variable.
When pthread_cond_wait() is called, the calling thread must own the mutex.
The thread then atomically blocks and releases the mutex. When another thread
calls pthread_cond_signal(cond), one thread that is blocking on the
condition variable is selected to be unblocked. That thread will return
from the pthread_cond_wait() call when it can reacquire the mutex.
Note -- that means that when a thread calls pthread_cond_wait(), it
must wait for two events to occur before it may unblock: first, another
thread must call pthread_cond_signal(), and then it must reacquire
the mutex.
- select(w, rfd, NULL, NULL, NULL): This usage of select() takes
as input a collection of read-only file descriptors (specified by a bit-set rfd,
and a size delimeter w). It returns when at least one of them has something
ready to read -- meaning that read() will not block when called on that
file descriptor. Rfd is modified to specify which of these file descriptors
are ready, and the return value of select() specifies how many file
descriptors are ready to read.
Grading: 8 Points
- pthread_mutex_lock(mutex): 2 points. 1 point for what happens on a
unlocked mutex, and 1 point for what happens on a locked mutex.
- pthread_cond_wait(cond, mutex): 3 points. 1 point for blocking and
releasing the mutex, 1 point for needing the signal call, 1 point for
reacquiring the mutex.
- select(w, rfd, NULL, NULL, NULL): 3 points: 1 point for specifying
what the input is, 1 point for specifying when select returns, and
1 point for specifying the output.