Teach you how to play with the operating system (semaphore and PV operation topics)

     Please read this special article carefully. I believe that if you are serious and read my article carefully, I think you, for the original intention of starting to click on this article, will definitely solve your doubts~~~~~ Then, look down~----------strugglestrugglestrugglestrugglestrugglestrugglestruggle

One: The essence of semaphore

   The data structure of a semaphore is a value and a pointer to the next process waiting for the semaphore. The value of the semaphore is related to the usage of the corresponding resource. When its value is greater than 0, it indicates the number of currently available resources; when its value is less than 0, its absolute value indicates the number of processes waiting to use the resource. Note that the value of a semaphore can only be changed by PV operations.

Two: the function of the semaphore mechanism

   Interprocess communication is a mechanism for handling synchronous mutual exclusion. A semaphore is a counter that can be used to control access to a shared resource by multiple processes. It is often used as a locking mechanism to prevent other processes from accessing a shared resource while a process is accessing the resource.

Three: the meaning of PV operation

   The PV operation consists of the P operation primitive and the V operation primitive (the primitive is an uninterruptible process), and the corresponding operation is performed on the semaphore.

Four: Definition of PV Operation

    Among them, S represents the value of the semaphore, P represents the P operation, and V represents the V operation;
    P(S): ①Reduce the value of the semaphore S by 1, that is, S = S-1;
            ②If S < 0, the process Enter the blocking queue;
      ③If S >= 0, the process continues to execute;
    ④Performing a P operation actually means requesting the allocation of a resource, so it is easy to understand for ② and ③, when the value of the semaphore is less than 0, Then it means that there are no available resources, then the process can only execute after waiting for other processes that own the resource to release the resources; when the semaphore is greater than 0, it means that there are still enough resources, so the current process can Continue to execute;
    V(S): ①Add 1 to the value of the semaphore S, that is, S = S + 1;
            ②If S > 0, the process continues to execute;
    ③ If S < 0, release the first block in the blocking queue A process waiting for a semaphore;
    ④ Performing a V operation actually means releasing a resource, so it is easy to understand for ② and ③. When the value of the semaphore is greater than 0, it means that there are available resources, then it means that the signal If the amount of resources is enough for the process to apply, there is no need to put the process into the blocking queue; and when the semaphore is less than 0, it means that for this semaphore, there are other processes that have already applied for the semaphore operation, but it was not enough for the process to obtain resources before. Simply put, it means that there are other processes in the blocking queue that have performed the P operation and are waiting for the semaphore. Therefore, in this case, the first process in the blocking queue is said. A process waiting for a semaphore can be processed;
   I think, through my explanation of PV operation and semaphore above, everyone should have a simple understanding of the whole process. It may be a bit confusing, but read what I wrote carefully, and try to figure it out slowly. , you should understand, this may not be very in line with our usual logic, but, after understanding it, you will feel that this is actually a benefit of PV operation. Below, I use an example to help you understand better.

Five: Example analysis of the processing between the semaphore and the PV operation

Example: There are now three processes A, B, and C, all of which are critical resources that require the semaphore S, and the initial value of the semaphore is 1 (so, when the three of them apply for resources, Only one process will get resources for execution)
Step 1: Fortunately, A enters the critical resource first, then it needs to perform the P operation, so the semaphore becomes S = 0 at this time;
Step 2: Then B also enters the critical resource, but A has not released the resource, and B performs the P operation to apply for the resource. Therefore, the semaphore becomes S = -1 at this time;
the third step: the same, and then C also enters the critical resource resource, but A has not released the resource yet, C performs the P operation to apply for the resource, so at this time the semaphore becomes S = -2;
(Through the previous three steps, the situation at this time is that A is executing normally, But it hasn't been executed and the resources have not been released, and B and C are both out of blocking queues, because there are not enough resources, so is it a good understanding here? Well, very good, let's continue!)
Step 4 : Wow, A has finally been executed, then since PV operations must appear in pairs, A must perform V operations, so at this time, A releases resources, and the semaphore becomes S = -1 (because S=-2 in the third step, and performing the V operation is equivalent to releasing a resource, so it becomes -1 here, which is not difficult to understand)
Step 5: Because A performs the V operation, it will wake up the first waiting process in the blocking queue, then it can be seen from the front that B is waiting first, so naturally B will wake up, so at this time, B will Start to enter the critical section for corresponding execution processing; (I think some friends may ask, now that B is operating in the critical section, shouldn't it be necessary to perform the P operation first to obtain resources? Everyone, please pay attention, No, because we know that B was actually woken up from the blocking queue, and the reason why it entered the blocking queue is because the P operation was performed before, resulting in not enough semaphores at that time for it to be able to perform Execute, so now it is only equivalent to the wake-up operation, and there is no need to perform the P operation again, just like the transition from the ready state to the execution state in our process. Because A executes the V operation, B goes from blocking to ready, when When there are resources, then B can naturally enter the running state, so is it better to understand? --- Note: This is an analogy to help everyone understand)
Step 6: After the execution of B is completed, Similarly, perform the V operation again, so, at this time, the semaphore S = 0
Step 7: Since B performs the V operation, it wakes up the first waiting process in the blocking queue, which is C, so at this time, C The resources of the critical section are obtained, then the execution can begin; the
eighth step: After the execution of C is completed, the V operation is also performed, so, at this time, the semaphore S = 1
Step 9: All three processes are executed Completed, and the blocking queue does not wait for the process, so is communication between processes achieved? And, have you found that from the beginning to the end, the value of the semaphore has not changed, all of which are S = 1. So, is it easy to understand? As mentioned, the value of the semaphore does not actually change. . At this point, basically, the communication of the process can be completed, and the PV operation is also over.
I think some friends may ask, if there is another process D coming and it also needs the same critical resources as ABC, what will happen at this time?
Step 10: It's very simple, because at this time S = 1, and S > 0, then if D comes at this time, you can execute it directly, that is, execute the P operation, so that S = 0, and then D executes the operation it needs, after the execution is completed Perform the V operation again, that is, to release the resource. At this time, S = 1, so this situation is back.
Step 11: According to the situation of step 10, if another process E comes at this time (wow, so many, it's abominable~~), what will happen? In fact, as long as we understand the working principle, it is easy to understand, then since S = 0 at this time, E cannot continue to execute, so E first performs the P operation, S = -1, and then is put into the blocking queue Go, and when the execution of D's use of resources is completed, since D performs the V operation, so S = 0, then wakes up the first one in the waiting queue, so E gets the opportunity to execute, then E starts to execute, After the execution is completed, the V operation is performed, so S = 1, obviously, it is the original state again.

Summary: I think, if I explain it through this example, it should be enough for everyone to understand the working principle. In addition, I also analyzed different situations. Friends, if you still don’t understand, please read it a few more times. If I still can't read it, then even if I lose it~~ haha~~

Six: The model of semaphore and PV operation to realize process communication (in fact, process mutual exclusion)

Reminder: When using PV operation to achieve process mutual exclusion, you should pay attention to:

    (1) In each program, the mutually exclusive P and V operations must appear in pairs , first perform the P operation, enter the critical section, and then perform the V operation to exit the critical section. If there are multiple branches, carefully check the pairing.
    (2) The P and V operations should be close to the head and tail of the critical section, respectively. The code of the critical section should be as short as possible, and there should be no infinite loop.
   (3) The initial value of the mutual exclusion semaphore is generally 1.

Seven: The classic problem

(1) Producers and consumers

(2) Readers and writers

(3) Philosophers eat

(4) The sleeping barber

Above, these four questions, I think, everyone has the general process of understanding them, and then, you can go back and look at these four classic questions based on your current understanding. I think, if you look at it now, there should be There are many differences. I won't talk about these issues here. In addition, I will give other examples to help you understand this problem further.

(5) The problem of dining seats in the cafeteria

Description: Now there is a cafeteria with 50 seats. After class is over, students have to eat in the cafeteria, and only when some students have finished eating, the seats will be opened, so that other students can sit. Therefore, such a process is implemented using the PV operation.

Parse: set semaphore sp = 50;

void student(void) // student process
{
        P(sp);
        dining;
        V(sp);
}
In fact, this situation is similar to the first common situation of producer and consumer (consumer, producer, public resource).

(6) The "harmonious relationship" between the cafeteria aunt and the students

Description: An aunt in the cafeteria is responsible for helping the students with meals, but the students cannot take the initiative to cook the meals themselves. They can only take the meals after waiting for the aunt to pick up the meals. The aunt is not allowed to eat during the meal time, but is only responsible for serving the students. meal.

Analysis: Set the number of rice that has been made: ricenumber = 0;

                  The number of plates for one meal: platenumber = 1;

void auntie( ) // Ali's meal process
{
    while(1)
    {
        P(platenumber); //Get the plate
        put a meal on a plate;
        V(ricenumber); //Increase the number of meals
    }
}

void student( ) // student process
{
    while(1)
    {
        P(ricenumber); //Get rice
        take the meal away from the plate;
        V(platnumber); //Release the plate

        eat apples;

    }
}

        I have made some analysis on the communication mechanism and PV operation of the semaphore in the operating system, as well as some examples of the application of PV operation. Technology to benefit our lives and learning. . Go Go Go , hand by hand~!

In addition, if you are interested, you can also read my article about the operating system, and pay attention ~ Of course, there are more other knowledge!laughing out loud

https://blog.csdn.net/Cs_hnu_scw/article/details/79896500

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325610675&siteId=291194637