Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 15.8 Semaphores 565


Example — Timing Comparison of Message Queues and Full-DuplexPipes


If we need a bidirectional flow of data between a client and a server, we can use either
message queues or full-duplex pipes. (Recall from Figure15.1 that full-duplex pipes are
available through the UNIX domain sockets mechanism [Section 17.2], although some
platforms provide a full-duplex pipe mechanism through thepipefunction.)
Figure15.27 shows a timing comparison of three of these techniques on Solaris:
message queues, full-duplex(STREAMS)pipes, and UNIX domain sockets. The tests
consisted of a program that created the IPC channel, calledfork,and then sent about
200 megabytes of data from the parent to the child. The data was sent using 100,000
calls tomsgsnd,with a message length of 2,000 bytes for the message queue, and
100,000 calls towrite,with a length of 2,000 bytes for the full-duplex pipe and UNIX
domain socket. The times areall in seconds.

Operation User System Clock
message queue 0.58 4.16 5.09
full-duplex pipe 0.61 4.30 5.24
UNIX domain socket 0.59 5.58 7.49

Figure 15.27 Timing comparison of IPC alternatives on Solaris

These numbers show us that message queues, originally implemented to provide
higher-than-normal-speed IPC, are no longer that much faster than other forms of IPC.
(When message queues wereimplemented, the only other form of IPC available was
half-duplex pipes.) When we consider the problems in using message queues
(Section 15.6.4), we come to the conclusion that we shouldn’t use them for new
applications.

15.8 Semaphores


Asemaphoreisn’t a form of IPC similar to the others that we’ve described (pipes,
FIFOs, and message queues). Asemaphore is a counter used to provide access to a
shared data object for multiple processes.
The Single UNIX Specification includes an alternative set of semaphoreinterfaces that were
originally part of its real-time extensions.We discuss these interfaces in Section 15.10.
To obtain a shared resource, a process needs to do the following:


  1. Test the semaphorethat controls the resource.

  2. If the value of the semaphore is positive, the process can use the resource. In
    this case, the process decrements the semaphorevalue by 1, indicating that it
    has used one unit of the resource.

  3. Otherwise, if the value of the semaphore is 0, the process goes to sleep until the
    semaphorevalue is greater than 0. When the process wakes up, it returns to
    step 1.

Free download pdf