Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 11.6 Thread Synchronization 407


tfp = tfp->f_next;
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
}else {
pthread_mutex_unlock(&hashlock);
}
}

Figure 11.12 Simplified locking

Note how much simpler the program in Figure11.12 is compared to the program in
Figure11.11. The lock-ordering issues surrounding the hash list and the reference count
go away when we use the same lock for both purposes. Multithreaded softwaredesign
involves these types of trade-offs. If your locking granularity is too coarse, you end up
with too many threads blocking behind the same locks, with little improvement
possible from concurrency.Ifyour locking granularity is too fine, then you suffer bad
performance from excess locking overhead, and you end up with complex code. As a
programmer,you need to find the correct balance between code complexity and
performance, while still satisfying your locking requirements.

11.6.3 pthread_mutex_timedlockFunction


One additional mutex primitive allows us to bound the time that a thread blocks when
amutex it is trying to acquire is already locked. Thepthread_mutex_timedlock
function is equivalent topthread_mutex_lock,but if the timeout value is reached,
pthread_mutex_timedlockwill return the error codeETIMEDOUTwithout locking
the mutex.
#include <pthread.h>
#include <time.h>
int pthread_mutex_timedlock(pthread_mutex_t *restrictmutex,
const struct timespec *restrict tsptr);
Returns: 0 if OK, error number on failure
The timeout specifies how long we arewilling to wait in terms of absolute time (as
opposed to relative time; we specify that we arewilling to block until time X instead of
saying that we arewilling to block for Y seconds). The timeout is represented by the
timespecstructure, which describes time in terms of seconds and nanoseconds.

Example


In Figure11.13, we see how to usepthread_mutex_timedlockto avoid blocking
indefinitely.
Free download pdf