Timing out on a mutex lock attempt

In the earlier section, Locking guidelines, under the label prevent starvation, we understood that holding a mutex lock for a long-ish time leads to performance issues; noticeably, the loser threads will starve. A way to ward off this issue (although, of course, fixing the underlying root cause of any starvation is the important thing to do!) is to have the loser threads wait upon the mutex lock for only a certain amount of time; if it takes longer to be unlocked, forget it. This is precisely the functionality that the pthread_mutex_timedlock(3) API provides:

#include <pthread.h>#include <time.h>int pthread_mutex_timedlock(pthread_mutex_t *restrict mutex,        const struct timespec *restrict abstime);

It's quite ...

Get Hands-On System Programming with Linux now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.