Semaphore is an important operating system concept proposed by Dijkstra in the Netherlands in order to solve the problem of concurrent processes.
Its basic idea:
Two or more processes can work together through simple signals. A process can be forced to stop at a certain position until it receives a specific signal. No matter what complicated cooperation needs, appropriate signal structures can be met. In order to send a signal, a special variable called a semaphore must be used. To send signals through semaphores, the process can run the primitive semsignal (s), that is, the V operation. To receive signals through semaphores, the process can run the primitive semwait (s), that is, the P operation; if the corresponding signal has not been sent, the process will be suspended until the sending location
Semaphores can be regarded as dead variables with integers. There are three operations:
1. A semaphore can be initialized to a non-negative number. Generally, the number of resources is the initial value of the semaphore.
2. semwait operation, that is, P operation, causes the semaphore to be reduced by 1. If the value is changed to negative (S <0), the process running semwait is blocked; otherwise, the process continues to run.
3. The semsignal operation, that is, the V operation, causes the semaphore to add 1. If the value is smaller than or equal to zero, the process blocked by the semwait operation will be lifted.
Pseudo code for P and V Operations:
# Include <queue> using namespace STD; struct semaphore {int count; queuetype queque;} void semwait (semaphore s) {// P operation S. count --; If (S. count <0) {place this process in S. queue; block this process;} void semsignal (semaphore s) {// v operation S. count ++; If (S. count <= 0) {remove a process P from S. queque; place PROCESS p on ready list ;}}
Semaphores (1) Basic knowledge