Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 15.10 POSIX Semaphores 583


Example


One of the motivations for introducing the POSIX semaphoreinterfaces was that they
can be made to perform significantly better than the existing XSI semaphoreinterfaces.
It is instructive to see if this goal was reached in existing systems, even though these
systems werenot designed to support real-time applications.
In Figure15.34, we comparethe performance of using XSI semaphores (without
SEM_UNDO)and POSIX semaphores when 3 processes compete to allocate and release
the semaphore1,000,000 times on two platforms(Linux 3.2.0 and Solaris 10).

Solaris 10 Linux 3.2.0
User System Clock User System Clock
Operation

XSI semaphores 11.85 15.85 27.91 0.33 5.93 7.33
POSIX semaphores 13.72 10.52 24.44 0.26 0.75 0.41

Figure 15.34 Timing comparison of semaphoreimplementations

In Figure15.34, we can see that POSIX semaphores provide only a 12%
improvement over XSI semaphores on Solaris, but on Linux the improvement is 94%
(almost 18 times faster)! If we trace the programs, we find that the Linux
implementation of POSIX semaphores maps the file into the process address space and
performs individual semaphoreoperations without using system calls.

Example


Recall from Figure12.5 that the Single UNIX Specification doesn’t define what happens
when one thread locks a normal mutex and a different thread tries to unlock it, but that
error-checking mutexes and recursive mutexes generate errors in this case. Because a
binary semaphorecan be used like a mutex, we can use a semaphore to create our own
locking primitive to provide mutual exclusion.
Assuming we were to create our own lock that could be locked by one thread and
unlocked by another,our lock structuremight look like
struct slock {
sem_t *semp;
char name[_POSIX_NAME_MAX];
};
The program in Figure15.35 shows an implementation of a semaphore-based
mutual exclusion primitive.
#include "slock.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
struct slock *
Free download pdf