[Operating system] 2.5 process management (synchronization and mutual exclusion of processes)

Process synchronization

The process is asynchronous. Asynchrony means that each concurrently executing process advances the
Insert picture description here
reading process and the writing process at an independent and unpredictable speed to execute concurrently. Since concurrency inevitably leads to asynchrony, the "write process" and the "read process" are two The order in which the operations are performed is uncertain. In practical applications, it must be executed in the order of "write data→read data".
How to solve this one-step problem is what is discussed in "process synchronization"

  • Process synchronization: Also known as the direct control relationship , it refers to two or more processes established to complete a certain task. These processes need to coordinate their work order in certain positions and produce the constraint relationship
  • The direct restriction between processes stems from their mutual cooperation

Process mutual exclusion

Two ways of sharing resources:

  1. Mutually exclusive sharing: Although some resources in the system can be provided to multiple processes, only one process is allowed to access the resource in a period of time
  2. Simultaneous sharing: certain resources in the system are allowed to be accessed by multiple processes "simultaneously" within a period of time (alternate access)
  • Put a period of time only allows a process to use resource known as the critical resources. Many physical devices (such as cameras and printers) are critical resources. In addition, many variables, data, memory buffers, etc. belong toCritical resource
  • Access to critical resources must be mutually exclusive. Mutually exclusive, that is, indirect restriction relationship .
  • Process mutual exclusion: Refers to when a process accesses a critical resource, another process that wants to access the critical resource must wait . The access of the process currently accessing the critical resource ends. After the resource is released, another process can access the critical resource.
  • Mutually exclusive access to critical resources can be logically divided into four parts
    Insert picture description here
    1. Entry zone : Responsible for checking whether you can enter the critical zone, if you can enter, you shouldSet the flag of accessing critical resources (locked), In order to prevent other processes from entering the critical area at the same time (when other processes want to access the critical resource, check the entry area and find that there is a process accessing the critical resource at this time)
    2. Critical section :accessCritical resource
    3. Exit zone : responsibleRemove the flag of accessing critical resources (unlock)
    4. Remaining area : do other processing
  • note:
    1. Critical section is a code segment that accesses critical resources in a process
    2. Entry area and exit area are code segments responsible for achieving mutual exclusion
    3. Critical section

Thinking:
If a process cannot enter the critical zone for the time being, can the process always occupy the processor? Is it possible that the process will never enter the critical section?

  • The principles that need to be followed to achieve mutually exclusive access to critical resources :
    1. Free to let in : critical sectionidleTime, you can let a process requesting to enter the critical sectionEnter nowCritical section
    2. Waiting if busy : WhenAlreadyWhen the process enters the critical section, other processes trying to enter the critical sectionHave to wait
    3. Limited waiting : the process requesting access should be guaranteed to be able toLimited timeEnter the critical zone (guaranteed not to be hungry)
    4. Give power to wait : When the process cannot enter the critical section, it shouldRelease the processor immediately to prevent the process from waiting(The process can't be executed, but it still occupies the processor)

The software realization method of mutual exclusion of processes

  1. Single sign method:

    1. Only check in the entry area without locking
    2. Transfer the right to use critical resources to another process in the exit zone
    3. Main problem: Does not follow the principle of letting in idle
  2. Double mark first check method:

    1. Check before entering the zone and then lock, and unlock the exit zone
    2. The main problem: do not follow the principle of busy and wait
  3. Double-mark post-inspection method:

    1. Check after the entry zone is locked first, and the exit zone is unlocked
    2. Main problem: Does not follow the principle of letting in idle and limited waiting
  4. Peterson algorithm:

    1. Take the initiative to fight in the entry zone-take the initiative to give in-check whether the other party wants to enter and whether you give yourself the last time
    2. The main problem: if you don’t follow the principle of giving power to wait, there will be busy waiting
  • Can take advantage of the processAsynchrony Check the shortcomings of these algorithms, check various execution sequences, and possible problems

Hardware realization method of mutual exclusion of processes

  1. Interrupt shielding method:

    1. Principle: The realization of "on/off interrupt instruction" is the same as the original realization idea, that is, when a process starts to access the critical area to the end position, it is not allowed to be interrupted, and process scheduling cannot occur, so it is impossible for two to happen. Processes simultaneously access critical resources
    2. Disadvantages:
      1. Not suitable for multi-processor systems, because shutting off interrupts on one processor does not prevent the process from executing the same critical section code on other processors
      2. It is only suitable for the kernel program of the operating system, not suitable for the user process, because the switch interrupt instruction can only be allowed in the kernel mode . If this group of instructions is used by the user at will, it will be very dangerous
  2. TestAndSet (TS instruction or TSL instruction)

    1. The TSL instruction is implemented by hardware, and it is not allowed to be interrupted during the execution, and can only be done in one go.
    2. advantage:
      1. In the previous double-mark first check method and double-mark second check method, the check and lock of the entry area are not done at one go. This causes P1 to check that the resource is not locked and can be accessed, but it will not be locked in the future. When process scheduling occurs , P2 is executed . At this time, P2 also finds that the resource is not locked, and it also thinks that it can access the critical resource, which causes the phenomenon that two processes access the critical resource at the same time. (The post-check method is to lock first and check later, so that there will be a phenomenon that neither resource can access the critical resource). butRealize check and lock operation by hardware, Can avoid logic loopholes in software implementation
      2. Suitable for multiprocessor operating system
    3. Disadvantages: The principle of giving power to wait is not satisfied. Processes that cannot enter the critical section temporarily occupy the processor and execute TSL instructions cyclically, resulting in busy waiting
  3. Swap instruction (XCHG instruction) (the principles and characteristics are the same as the TSL instruction)

⭐Semaphore mechanism

Thinking: Problems with previous methods

  1. In the double-mark inspection method, the inspection and locking of the entry zone are not done at one go, and there are logical loopholes.
  2. All previous algorithms did not follow the principle of "giving power to wait", (when it is checked that the critical resource cannot be accessed, it will always execute the while statement and wait in a loop)
  • The user process can use a pair of primitives of the operating system to operate on the semaphore, so as to easily achieve mutual exclusion and synchronization of processes
  • signal In fact, it is a variable (it can be an integer or a more complex record variable). A semaphore can be used to indicate the amount of a certain resource in the system. For example, if the system has only one printer, you can set an initial value 1 semaphore
  • PrimitiveIt is a special program segment whose execution can only be done in one go and cannot be interrupted . The primitive is realized by the off interrupt/open interrupt instruction . The problem with the previous software solution is that "the operations of entering the zone cannot be done in one go." Therefore, if the operations of entering and exiting the zone can be implemented with "primitives", these operations can be completed in one go to avoid the problem.
  • A pair of primitives: wait(s) primitive and signal(s) primitive. The primitive can be understood as a function written by ourselves . The function names are wait and signal respectively. The semaphore s in parentheses is the function call time transfer Incoming parameters
  • The primitives of wait and signal are called P and V operations for short , so a pair of primitives can be written as P(s), V(s)
  • Semaphore mechanism classification
    1. Integer semaphore: Use an integer variable as a semaphore to indicate the amount of a certain resource in the system

        //整型信号量定义
        int S = 1;        	 //初始化整型信号量,表示当前系统中可以使用的打印机资源数
        void wait(int S){
              
               	//wait原语,相当于进入区
        	while(S<=0);   		//检查,如果资源不够就一直循环等待(一直在while中循环)导致会发生忙等
       	S=S-1;        		 //上锁,如果资源够,则占用一个资源
        }
        void signal(int S){
              
               	//signal原语,相当于退出区
        	S=S+1;           	//解锁,使用完资源后,在退出区释放资源
        }
      
        //进程P0:
        ...
        wait(S);			//进入区,申请资源
        使用打印机资源...	//临界区,访问资源
        signal(S);		//退出区,释放资源
        ...
      
      1. The difference with ordinary integer variables: There are only three operations on semaphores, namely initialization, P operation, and V operation
      2. Advantages: check and lock in one go, avoiding problems caused by concurrency and asynchrony
      3. Disadvantages :If you don’t meet the principle of giving power to wait, busy waiting will happen
    2. ⭐Recording semaphore: The disadvantage of integer semaphore is busy and other issues, therefore, the semaphore represented by a record-type data structure is proposed

      //记录型信号量的定义
      typedef struct{
              
              
      	int value;			//资源数
      	struct process *L;	//指向阻塞队列的指针
      } semaphore;
      
      void wait(semaphore S){
              
              
      	S.value--;			//使用一个资源,将资源数减一
      	if (S.value<0){
              
              		//如果资源数减一后发现其小于0,说明当前资源不够用
      		block(S.L);	//使用block原语使进程从运行状态进入阻塞态,并把它挂到信号量S的等待队列中
      	}
      }	
      
      void signal(semaphore S){
              
              
      	S.value++;		//释放一个资源,将资源数加一
      	if (S.value <= 0){
              
              	//若释放后,资源数小于等于0,则说明在释放之前,有进程正在等待刚被释放的资源
      		wakeup(S.L);	//故使用wakeup原语从等待队列中唤醒一个进程,该进程从阻塞态变为了就绪态
      	}
      }
      

      Example:
      There are two printers in a computer, when initializing the semaphore S, the value of S.value is set to 2, and the queue SL is set to null
      Insert picture description here
      Insert picture description here

      1. First, P0 applies for a printer, after executing the wait primitive, the resource number value becomes 1, and then P1 applies for a printer, and the value becomes 0
      2. P2 applies for a printer, and then in the wait operation of P2, the value value is reduced by one to -1 (indicating: a process is waiting) , and then it is judged that value<0, so use the block primitive to hang the P3 process on the blocking queue
      3. P3 applies for a printer, and then in the wait operation of P3, the value value is reduced by one to -2 (indicating: two processes are waiting) , and then it is judged that value<0, so use the block primitive to hang the P3 process on the blocking queue
      4. When the P0 process finishes using the printer, it executes the signal primitive, the value of the resource number plus one is -1 (indicating that there is a process waiting for the printer), and then judges that value<=0, it executes the wakeup primitive and wakes up from the blocking queue The P2 process at the head of the queue and assign the printer to P2
      5. P2 directly uses the printer resource ( no need to execute the wait primitive to apply ), and then executes the signal primitive to release the printer, the value is increased by one to 0, and it is judged that value<=0 (indicating that there are processes waiting for the printer in the blocked queue), and then execute wakeup The primitive wakes up the P3 process, P3 changes from the blocked state to the ready state, the printer released by P2 is allocated to P3, and then P3 uses the printer directly. . .
      6. If the P1 process runs out of the printer at this time, the signal primitive releases the resource, and the value is incremented to 1. At this time, it is judged that value>0, indicating that no process is blocking the queue waiting for the printer at this time, and the wakeup primitive will not be executed.

      summary:

      1. wait(S) and signal(S) can also be denoted as P(S) and V(S). This pair of primitives can be used to implement system resources "Application" with "freed"
      2. S.valueInitial valueIndicates the number of a certain resource in the system
      3. A P operation on the semaphore S means that the process requests a unit of this type of resource, so S.value--needs to be executed, which means that the number of resources is reduced by one, when value<0 Time, it means that the resource has been allocated, so the process should callblockThe primitive self-blocks (the currently running process enters the blocking state from the running state), actively abandons the processor , and hangs to the end of the waiting queue SL of the resource, so that the principle of giving power to wait is realized, and there will be no busy waiting The problem (will not always execute the while loop as before, waiting for resources)
      4. A V operation on the semaphore S means that the process releases a unit of this type of resource, so it needs to execute S.value + +, which means that the number of resources plus one, when value<=0 Time, it means that there are still resources waiting for the resource, so callwakeupPrimitive, wake up the head process from the blocking queue (the awakened process enters the ready state from the blocked state), and assign the printer to the process. At this time, the process has already obtained the printer. If it is its turn to use the processor, it You can no longer execute the wait primitive to apply for a printer, but you can directly use the printer to work

Semaphore mechanism to achieve mutual exclusion of processes

  1. Analyze the key activities of concurrent processes and delimit the critical area (for example: access to the critical resource printer should be placed in the critical area)
  2. Set upMutexInitial value is 1(Here willCritical sectionSeen as a special resource, and there is only one such resource )
  3. in Before the critical section Perform P (mutex)
  4. in After the critical section Execute V (mutex)
  5. note:
    1. For different critical resources, different mutually exclusive semaphores need to be set (printer: mutex1; camera: mutex2;...)
    2. P and V operations must appear in pairs (the lack of P operation cannot guarantee the exclusive access of critical resources; the lack of V operation will cause the resource to never be released, and the waiting process will never be awakened)
	//信号量机制实现互斥
	semaphore mutex =1;	//初始化信号量
	 
	 P1(){
    
    
	 	...
	 	P(mutex);		//上锁
	 	临界区代码段...
	 	V(mutex);		//解锁
	 	...
	 }

 	P2(){
    
    
	 	...
	 	P(mutex);		//若P1还为使用完,此时资源数为-1,所以block原语会将P2进程挂到阻塞队列上
	 	临界区代码段...
	 	V(mutex);
	 	...
	 }

Semaphore mechanism to achieve process synchronization

  • Process synchronization: Let each concurrent process proceed in an orderly manner as required
    P1(){
           
           
    	代码1;
    	代码2;
    	代码3}
    P2(){
           
           
    	代码4;
    	代码5;
    	代码6}
    

    For example, P1 and P2 are executed concurrently. Due to the asynchronous nature, the order of the alternate advancement of the two is uncertain.
    If the execution of code 4 needs to use the execution result of code 2, it is required that code 4 must be executed after code 2. At this time, the relationship is synchronized, coordinated with each other, and promoted

  • Use semaphore mechanism to achieve process synchronization
    1. Analyze where the synchronization relationship needs to be achieved, that is, the two operations that must be guaranteed "one tandem" **
    2. Set the amount of synchronization signal S , the initial value is 0
    3. in "Pre-operation"carried outRear Perform V(S)
    4. in "Post-operation"carried outbefore Perform P(S)
     	//信号量机制实现进程同步
      	semaphore S=0;
     	P1(){
          
          
     		代码1;
     		代码2V(S);		//前操作执行后V
     		代码3}
     	P2(){
          
          
     		P(S);		//后操作执行前P
     		代码4;
     		代码5;
    		代码6}
    
    1. If P1 executes the V(S) operation first , then S++ is followed by S=1, and then when P2 executes P(S) , since S=1, it means that there are available resources, S--will be executed, and the value of S will become 0. Does not meet <0, so the block primitive will not be executed, but code 4 will continue to be executed
    2. If P2 performs the P(S) operation first , then S--then S= -1, which means that there are no available resources at this time, so the block primitive will be called, and the process P2 will actively block. When P1 finishes executing code 2, then execute V (S) , at this time S++, then S=0, then the wakeup primitive will be called to wake up P2 in the blocking queue, so that P2 can continue to execute code 4
    3. In this way, the synchronization relationship of code 4 must be executed after code 2

The semaphore mechanism realizes the precursor relationship (synchronous expansion)

Actually is the expansion of synchronization relationship realization

  • For example: the processes are executed in the order shown in the figure:
    Insert picture description here
  • In fact, every pair of predecessor relations is a process synchronization problem (need to ensure one-to-one operation)
    1. To set a synchronization variable for each predecessor relationship
    2. in"Pre-operation"OfRearPerform V operation on the corresponding synchronization variable
    3. in"Post-operation"OfbeforePerform P operation on the corresponding synchronization variable
//信号量机制实现前驱关系
semaphore a=0;		//要为每一个前驱关系各设置一个同步变量
semaphore b=0;
semaphore c=0;
semaphore d=0;
semaphore g=0;

P1(){
    
                           P2(){
    
        					 P3(){
    
         
    ... 						...							...
    S1;							P(a);						P(a);
	V(a);						S2; 						S3;
    V(b);						V(c);						V(g);
	...							V(d);						...
}								...						}
							}

Guess you like

Origin blog.csdn.net/Qmilumilu/article/details/112973036
Recommended