ptg10805159
436 Thread Control Chapter 12
main
func1(x)
func2(x)
func1
pthread_mutex_lock(x->lock)
func2_locked(x)
pthread_mutex_unlock(x->lock)
func2
pthread_mutex_lock(x->lock)
func2_locked(x)
pthread_mutex_unlock(x->lock)
func2_locked
Figure 12.7 Avoiding a recursive locking opportunity
Example
The program in Figure12.8 illustrates another situation in which a recursive mutex is
necessary.Here, we have a ‘‘timeout’’function that allows us to schedule another
function to be run at some time in the future. Assuming that threads are an inexpensive
resource, we can create a thread for each pending timeout. The thread waits until the
time has been reached, and then it calls the function we’ve requested.
The problem arises when we can’t create a thread or when the scheduled time to
runthe function has already passed. In these cases, we simply call the requested
function now,fromthe current context. Since the function acquires the same lock that
we currently hold, a deadlock will occur unless the lock is recursive.
#include "apue.h"
#include <pthread.h>
#include <time.h>
#include <sys/time.h>
extern int makethread(void *(*)(void *), void *);
struct to_info {
void (*to_fn)(void *); /* function */