format | wait()/P operation |
signal()/V operation | ||
---|---|---|---|---|
Integer | int S = 1; | while(s<=0); S=S-1; |
S=S+1; | May be busy waiting |
Record type | type struct{ int value; struct process *L; } S |
S.value--; if(S.value<0) //Hang the process into the waiting queue of the semaphore //And use the block primitive to block itself //Abandon the processor actively block(S.L); |
S.valus ++; if(S.value <=0) //If the semaphore is less than or equal to 0 after the resource is released //That is, there is still a process waiting for the resource, then wakeup through wakeup wakeup(S.L); |
Not busy waiting Will voluntarily give up the right to use the processor |
A semaphore actually represents a resource, and its value represents the remaining amount of resources
P operation: request resources, block if not requested
V operation: release the resource, wake up if there is a process waiting for the resource
Use semaphores to achieve mutual exclusion of processes
记录性型号量 mutex = 1;
p1(){
P(mutex);
//临界区代码
V(mutex);
}
P2(){
P(mutex);
//临界区代码
V(mutex);
}
note! ! ! Different semaphores should be set to represent different resources
P and V operations must be expressed in pairs
Use semaphore mechanism to achieve process synchronization
Set the initial value of the semaphore to 0
记录型信号量 S = 0;
P1(){
代码1;
代码2;
V(S);
代码3;
}
P2(){
P(S);
代码4;
代码5;
}
Used to ensure that the execution of code 4 is after code 2
Perform the V operation after each "pre-operation" to tell another process that it can continue execution
Perform P operation before each "post-operation", which is used to wait for another process to execute after the executed operation