Interprocess communication (6): Semaphore

signal

Semaphore (Semaphore), also known as light, the story comes from the Netherlands: Train to decide whether to pass according to the flag. In fact, the role of traffic lights. As shown in FIG.

By understanding the semaphore signals and traffic lights, they seem to feel the same. However, semaphore mechanism is based on the events people waiting for traffic lights (the process of blocking) or wait (process continues to run), only these two acts; and signaling mechanism is made of any possible event processing according to the traffic lights, not necessarily wait (blocking) or forward (not blocked).

In the computer field, the amount of signal is an integer value, if positive, indicates how many semaphores have also represents the number of lights can be used, the semaphore's value may be zero or negative. Binding to PV semaphore operation (two primitives) to the real work, P semaphore operation is a subtraction, V add a semaphore operation.

There are many semaphores variants, one of the following brief description of semaphores rules:

  • 1. If a process requests operation P (decremented, i.e. request a traffic light), the value after subtracting the amount of signal is negative, the process is blocked, after subtracting is 0 or a positive number, then the process release
  • 2. If a process requests V operation (operation plus 1, i.e. a light release or increase), the process directly release
  • 3. If the request V operation, if still after the addition of 1 0 or negative, then the process also release other blocked wakeup process. If, after adding 1 is a positive number, then add a direct resource lights

To sum up is simple: if no semaphore resources (less than or equal to 0), then the lights consumption (P primitive) process will be blocked; if there are lights resources (greater than 0), direct release. If a process is used to produce light resource (V primitive), then the process of course, to be released; because adding a traffic light, you can also wake up a blocked process has the ability (if there is, then the process is blocked).

The easiest course is to use only the amount of signal lights when an initial order to achieve mutual exclusion lock (also known as mutex) mechanism: P lock operation is to apply only when there is a value of 1 to apply for the lock, otherwise obstruction; V is to release a lock has been released.

Guess you like

Origin www.cnblogs.com/liujunjun/p/12411712.html