Operating System Principles Chapter 6 Process Synchronization

Operating System Principles Study Record for Undergraduates

learning record family bucket

6.1 Race Conditions and Critical Sections

6.1.1 Race conditions

Effective ways to prevent race conditions include: synchronization and mutual exclusion

6.1.2 Critical Sections

A resource that only allows one process to use at a time is called a critical resource, called a mutually exclusive resource, an exclusive resource, or a shared variable

A resource that is allowed to be used by more than one process at a time is called a shared resource

Critical section: is a section of code that involves critical resources

A few notes:

  • A critical section is a code fragment

  • A critical section is code within a process

  • Each process has one or more critical sections

6.1.3 Guidelines for Using Critical Sections

Mutual exclusion:

  • Assuming that a process P1executes in a critical section, other processes will be excluded from this critical section
  • Critical sections with the same critical resource need to be mutually exclusive
  • Critical sections without the same critical resource are not allowed to be mutually exclusive

Available to give in:

  • There is no process execution in the critical section, and the waiting time for the next process to enter the critical section cannot be extended indefinitely.
  • That is, when other processes want to enter, let them enter

Bounded waiting:

  • Each process must have a finite amount of time to wait before entering a critical section
  • can't wait forever

Let the right wait:

  • When a process wants to enter the critical section and finds that it cannot enter, it should actively release the control of the CPU and let other processes occupy the control of the CPU.
  • Running becomes waiting state

Access to critical section procedures

  • Implementing Mutual Exclusion Criteria in Entry Zones
  • Implementation of free-to-go criteria in the exit area
  • Each critical section cannot be too large to achieve bounded wait criterion

Two processes P0 P1, only algorithms for two processes

do {
    
    
    flag[i] = true;
    turn = j;
    while (flag[j] and turn == j);
    critical section;
    flag[i] = false;
    remainder section;
}while(1);

6.2 Semaphore (important)

6.2.1 Physical meaning of semaphore

Ensure that two or more code segments are not called concurrently

Before entering the critical code segment, the process must obtain a semaphore, otherwise it cannot run

After executing the key code segment, the semaphore must be released

The semaphore has a value, if it is positive, it means it is free, and if it is negative, it means it is busy

S>0: There are S resources available
S=0: No resources are available
S<0: Then |S| indicates the number of processes in the S waiting queue

P(S): Apply for a resource
V(S): Release a resource

Initial value of mutual exclusion semaphore: generally 1
Initial value of synchronous semaphore: 0-N

6.2.2 Integer semaphores

Semaphore S - integer variable

Provides two inseparable [atomic operations] to access the semaphore

wait (S): 
		 while S <= 0 do no-op;		
                S--;
signal(S): 
			S++;

Wait(S) also known as P(S)

Signal(S) also known as V(S)

Problems with integer semaphores: busy waiting

6.2.3 Recorded semaphores

Remove busy-wait semaphore

记录型信号量定义:

typedef struct {
    
    
	int value;
	struct process *list;
} semaphore
Wait(semaphore *S) 
{
    
    
	S->value--;
	if (S->value < 0) {
    
    
		add this process to list S->list;
		block();   //阻塞自身
	}
}

Signal(semaphore *S) {
    
    
	S->value++;
	if (S->value <= 0) {
    
    
		remove a process P from list S->list;
		wakeup(P);  //唤醒的是其他进程,P变为ready状态
	}
}



The use of semaphore S:

  • S must be set once and the initial value can only be set once
  • The initial value of S cannot be negative
  • Except for initialization, S can only be accessed by performing P, V operations

6.2.4 Mutex semaphores

Binary semaphore is also called mutual exclusion semaphore, semaphore S can only take 1 or 0

Semaphore *S;
S.value = 1;          全局变量,可以先这么理解

wait(S);
CritiaclSection()            //临界区
signal();

6.2.5 Synchronous semaphores

Realize various synchronization problems and disperse them into different processes. How to obtain the value of the initial value problem of S also requires observation and thinking

Example: P1and P2needs to be run C1beforeC2

semaphore s = 0

P1:

​	C1:

​	signal(s); //运行完了之后要告诉 C1,我运行完了

P2:

​	wait(s);      //因为一开始 S 为0,如果C1不执行,C2就会阻塞

​	C2;         //判断C1有没有运行

6.2.6 Small example

Students in two groups AB can take turns throwing the ball, how to achieve

Apply for multiple semaphores, cross each other

semaphore s1 = 0;
semaphore s2 = 1;


A :
while(1) {
	wait(S2);
	C1:投球
	signal(S1);
}


B:
while(1) {
	wait(S1);
	C2:投球
	signal(S2);
}

driver conductor problem

What is the synchronization problem between them:

Close the door to start the vehicle, close the door first, then start

Wait() P

Signal() V

semapheore s1 = 0
           s2 = 0

司机:
	P(s1)
C2:	启动车辆
	正常行驶
C3:	到站停车
	V(s2)
	
	
	
售票员:
C1:	关门
	V(s1)
	售票
	P(s2)
C4:	开门

6.3 Classic synchronization problem

6.3.1 Producer-Consumer Problem

shared limited buffer problem

The synchronization operation of wait precedes the synchronization operation of mutex

Problem Description

Producers (M): Produce products and put them in the buffer

Consumers (N): Take product consumption from the buffer

Question: How to achieve synchronization and mutual exclusion between producers and consumers

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-vO8n6dU4-1641539727576) (E:\Documents and PPT\Junior Course Study\Operating System\Pictures\Sixth Chapter\producer consumer problem.png)]

problem analysis process

Producer's production process: produce a product and put it in the buffer

The consumer's consumption process: take a product from the buffer and consume the product

Mutual exclusion problem analysis:

Mutual exclusion problems are often generated between the same process, and the mutual exclusion operation is performed on the critical section.

How to find the critical area, we must first find the critical resources, critical resources are often operations performed by a class of processes but limit the range of operations that can only be performed by one process at a time

In this problem, the critical resource of the producer is to put into the buffer, and the critical resource of the consumer is to take out the product from the buffer

Synchronization problem analysis:

Synchronization problems often occur between different types of processes. Generally , when a process of this type performs P operation and S decreases, another type of process needs to perform V operation to add this semaphore to maintain balance.

The parts that need coordination between the two:

  • Producer: Put the product into the specified buffer (key code C1)
  • Consumer: Take a product from the full buffer (key code C2)

Solution

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-KDUU2KLR-1641539727605) (E:\Documents and PPT\Junior Course Study\Operating System\Pictures\Sixth Chapter\Producer Consumer Problem 01.png)]

Deformation problem:

  1. The buffer has only one size
  2. Many different producers, one consumer (there is one assembler, who assembles products. Producer 1 produces a part, producer 2 produces a product 2, producer 3 produces 3, and then assembles into a product
  3. One producer, multiple different consumers (corresponding to the father putting the fruit on the plate, there are oranges - the daughter eats them, and the son eats the apples)
  4. Several S processes send messages, S1 and S2 send messages to be received by C1; S3 and S4 send messages to be received by C2

6.3.2 The reader-writer problem

Problem Description

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-EqYepqlE-1641539727613) (E:\Documents and PPT\Junior Course Study\Operating System\Pictures\Sixth Chapter\Reader Writer Problem Description.png)]

Solution

Set the semaphore W to 1, as a mutually exclusive semaphore, which acts on the fact that the writer cannot write and read and write at the same time

For problems that can be read by multiple readers at the same time, set a semaphore M, and the initial value of the counter cnt is 0

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-i5mXgxr6-1641539727617) (E:\Documents and PPT\Junior Course Study\Operating System\Pictures\Sixth Chapter\Reader Writer Problem Solution.png)]

6.3.3 The dining philosophers problem

If analyzed according to the general method, there will be a deadlock problem, that is, two adjacent philosophers have chosen the chopsticks on their left, so that some philosophers cannot get the chopsticks on the right because they are used by other philosophers. , this will eventually lead to a deadlock.

Problem Description

5 philosophers,
5 chopsticks
Each philosopher has a chopstick on the left and right
Each philosopher can only eat with two chopsticks on the left and right

Measures to prevent deadlock

Method 1: Only four philosophers can sit at a table and eat

Method 2: Pick up chopsticks only when the philosopher's left and right chopsticks are available

Method 3: Number all the philosophers. The philosophers with odd numbers can only pick up the chopsticks on the left first, and vice versa for even numbers.

method one

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-p6CXQj28-1641539727625) (E:\Documents and PPT\Junior Course Study\Operating System\Pictures\Sixth Chapter\The Philosopher's Method 1.png)]

Method Two

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-HVMAGzKc-1641539727633) (E:\Documents and PPT\Junior Course Study\Operating System\Pictures\Sixth Chapter\The Philosopher's Method II 01.png)]

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-APAEDyoU-1641539727639) (E:\Documents and PPT\Junior Course Learning\Operating System\Pictures\Sixth Chapter\The Philosopher's Method II 02.png)]

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-6B7dzFnw-1641539727641) (E:\Documents and PPT\Junior Course Study\Operating System\Pictures\Sixth Chapter\The Philosopher's Method II 03.png)]

MOOC unit work

1. What is a critical section? What guidelines should be followed for access to critical sections?

critical section:

The piece of code that accesses critical resources.

Guidelines:

  • Mutual exclusion, if a process is executed in a critical section, other processes will be excluded from the critical section, critical sections with the same critical resources need mutual exclusion, critical sections without the same critical resources do not need mutual exclusion.

  • If there is time to give way, there is no process execution in the critical area. A process that requests to enter the critical area should be allowed to enter its own critical area immediately to effectively use critical resources.

  • Limited waiting, the waiting time before each process enters the critical section must be limited, so as not to fall into a "dead wait" state.

2. Please talk about the meaning of the value of the synchronous semaphore.

When the value of the synchronous semaphore is greater than 0, it means that the amount of this resource is not used, or the amount released can be allocated to the process that requests to use this resource.

When the value of the synchronous semaphore is equal to 0, it means that this resource has been allocated or has not been released. If there is a process applying for this resource now, it must wait.

When the value of the synchronous semaphore is less than 0, it indicates that the requested resource has not been obtained and is waiting for the number of this resource.

3. There are four processes S1、R1、R2and R3, among them, S1send messages to the buffer BUFF, R1、R2and R3receive messages from the buffer. The rules for sending and receiving are as follows:
(1) The buffer BUFF can only store one message at any time;
(2) R1、R2Each message stored in the buffer R3can be retrieved; (3) Each message stored in the buffer must It can only be cleared after being received by both . Please use the semaphore mechanism to realize the synchronization between these 4 processes.S1
R1、R2R3

信号量初值 S1 = 1   R1 = 0  R2 = 0  R3 = 0  MUTEX = 1
int count = 0;

S1{
    
              R1{
    
                 R2{
    
                R3{
    
    
P(S1);         P(R1);          P(R2);        P(R3);
Send message;  Get message;    Get message;  Get message;
   					
P(MUTEX);      P(MUTEX);       P(MUTEX);      P(MUTEX);
V(R1);         count += 1;     count += 1;    count += 1;
V(R2);         if count == 3   if count == 3  if count==3
V(R3);	          V(S1);      	V(S1);      	V(S1);
V(MUTEX);         V(MUTEX);     V(MUTEX);      V(MUTEX);
}              }               }              }

4. There is an empty fruit plate on the table, and only one fruit can be placed in the plate at a time. Dad puts apples on the plate, mother puts oranges on the plate, a son waits to eat the oranges on the plate, and a daughter waits to eat the apples on the plate. It is fixed that father or mother can put a fruit on the plate every time when the plate is empty, and only when the plate has the fruit he needs, the son or daughter can take it out from it. Please use PVoperations to synchronize the four processes of father, mother, son and daughter.

信号量  Plate = 1    Orange = 0  Apple = 0
    
Dad{
    
                      Mum{
    
                   Son{
    
                        Daughter{
    
    
    while(true){
    
          while(true){
    
           while(true){
    
                while(true){
    
    
       P(Plate);      	P(Plate);        	P(Orange);           P(Apple);
    	put apple;    	put orange;         take the orange;     take the apple;
    	V(Apple); 		V(Orange);          V(Plate);            V(Plate);
    }                 }                     eat the orange;      eat the apple;
         				                 }                       }
    
}                     }                  }                       }

Process Management Exercises

There is a warehouse that can hold two kinds of items A and B,

设有两个信号量  a = N  b = M


In the bicycle production line, three workers perform their duties. Write out management questions.

A certain bridge is so narrow that it can only accommodate one car. From south to north, if one side has no cars, the other side can pass continuously.

If both sides have cars waiting, pass alternately. Set each vehicle as a process, and design semaphores to realize synchronous management

Guess you like

Origin blog.csdn.net/weixin_45788387/article/details/122365152