Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 15.9 Shared Memory 571


byte; to release it, we unlock the byte. The recordlocking properties guarantee that if a
process terminates while holding a lock, the kernel automatically releases the lock.
To use a mutex, we need both processes to map the same file into their address
spaces and initialize a mutex at the same offset in the file using the
PTHREAD_PROCESS_SHAREDmutex attribute. To allocate the resource, we lock the
mutex; to release the resource, we unlock the mutex. If a process terminates without
releasing the mutex, recovery is difficult unless we use a robust mutex (recall the
pthread_mutex_consistentfunction discussed in Section 12.4.1).
Figure15.29 shows the time required to perform these three locking techniques on
Linux. In each case, the resource was allocated and then released 1,000,000 times. This
was done simultaneously by three different processes. The times in Figure15.29 arethe
totals in seconds for all three processes.

Operation User System Clock
semaphores with undo 0.50 6.08 7.55
advisory recordlocking 0.51 9.06 4.38
mutex in shared memory 0.21 0.40 0.25

Figure 15.29 Timing comparison of locking alternatives on Linux

On Linux, recordlocking is faster than semaphores, but mutexes in shared memory
outperform both semaphores and recordlocking. If we’relocking a single resource and
don’t need all the fancy features of XSI semaphores, recordlocking is preferred over
semaphores. Thereasons arethat it is much simpler to use, it is faster (on this
platform), and the system takes care of any lingering locks when a process terminates.
Even though using a mutex in shared memory is the fastest option on this platform, we
still prefer to use recordlocking, unless performance is the primary concern. Thereare
two reasons for this. First, recovery from process termination is moredifficult using a
mutex in memory shared among multiple processes. Second, theprocess-sharedmutex
attribute isn’t universally supported yet. In older versions of the Single UNIX
Specification, it was optional. Although it is still optional in SUSv4, it is now required
by all XSI-conforming implementations.

Of the four platforms covered in this text, only Linux 3.2.0 and Solaris 10 currently support the
process-sharedmutex attribute.

15.9 Shared Memor y


Shared memory allows two or moreprocesses to shareagiven region of memory.This
is the fastest form of IPC, because the data does not need to be copied between the client
and the server.The only trick in using shared memory is synchronizing access to a
given region among multiple processes. If the server is placing data into a shared
memory region, the client shouldn’t try to access the data until the server is done.
Often, semaphores areused to synchronize shared memory access. (But as we saw at
the end of the previous section, recordlocking or mutexes can also be used.)
Free download pdf