Computer Operating System Fundamentals (4)-Process Synchronization of Process Management

introduction

This article is the fourth article, process synchronization of process management . This article mainly introduces why inter-process synchronization is needed and the principles of inter-process synchronization and thread synchronization

One, why need inter-process synchronization

Through two examples to understand what is process synchronization and why process synchronization is needed

(1) Producer-consumer problem

Problem Description: A group of producers process in the production of products, and these products available to the consumer process to consume, producer process and the consumer process can execute concurrently , between the two have set up a buffer n buffer Pool, the producer process needs to put the produced product in a buffer, and the consumer process can take the product from the buffer for consumption

Process of production and consumption

When a producer produces a product, the product in the buffer zone will be +1. Similarly, if a consumer consumes a product from the buffer zone, the product in the buffer zone will be -1. There is no such model in life. Problematic (for example, a mobile phone factory that produces a mobile phone on the assembly line will be placed in the warehouse, and consumers will take the mobile phone out of the warehouse for consumption. This producer-consumer model has no problem from a macro perspective)
Insert picture description here

The above model is fine from a macro perspective, but there will be problems when viewed from a computer micro perspective.
In the computer, this buffer is located on the cache or main memory . If the producer or consumer wants to manipulate the data in it, it is divided into three steps:

a. Take out the data and put it in the register register=count

b. Register+1 and register=register+1 in the registers of the CPU indicate that the producer has completed a product

c. Put register back into the buffer count=register

These three steps are the three necessary steps for us to operate the buffer. We can think of the buffer as a warehouse, and the register as the place of the producer or the place of the consumer. At first glance, this model does not seem to be a problem.
Insert picture description here

It is okay to look at the producer program or consumer program alone, but if the two are executed concurrently , there may be errors

The red part below is the production process by the producer, and the blue part is the consumer consumption process

Regarding register and count as the value of two parts (assuming 10), suppose that the first step of the producer is executed at this time, that is, register=count , at this time both are 10 , and then the second part of the producer is executed Step, register=register+1 , at this time the value in the register is +1, then at this time register=11, count=10 , assuming that the producer program and the consumer program are executed concurrently , then the third step is possible It is the consumer 's turn to execute, then suppose it is the first step of the consumer register=count , then the value of the register in the consumer's process is 10 at this time , and then the fourth step is executed, assuming the fourth step is executed The second step of the consumer, that is, register=register-1 . At this time, the value of the register of the consumer's process becomes 9 , and the value in the cache is still 10. Then perform the fifth step, and the fifth step assumes execution The third step to the consumer is count=register , that is, the value in the register is written back to the buffer. At this time, the value of the buffer and the consumer's register are both 9, and the consumer's operation is completed here , And then there is a producer operation, write the producer's register back to the buffer, then just now, the producer's register is equal to 11, Then after executing this step, it will rewrite register back to the buffer, then the value in the buffer becomes 11, count=register . In fact, there is a problem with this look. At the beginning, the value of the buffer was 10, and the +1 and -1 operations were performed during the execution, then its value should still be 10, but after the lease it becomes 11, indicating that the data is wrong. The reason for the error is that the two processes are executing concurrently . They are operating the buffer in turn, resulting in inconsistent data in the buffer. This is a producer-consumer problem

Let’s look at an example of actual execution. Below is a simple program that uses two threads to simulate the process of producer and consumer:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <vector>

pthread_ mutex t mutex = PTHREAD MUTEX INITIALIZER;
int num = 0;//全局变量,初始值为0
void *producer(void*){//生产者
      int times = 10000000 ;
      while(times -- ){//生产者将num循环+1很多次,表示生产过程,消费者是循环-1
      //pthread mutex_ lock (&mutex) ;
      num+=1;
      //pthread mutex unlock (&mutex) ;
  }
}

void *comsumer (void* ){//消费者
      int times = 10000000 ;while(times -- ){
      //pthread mutex lock (&mutex) ;
      num  -=  1;
      //pthread mutex unlock (&mutex) ;
  }
}

//在main函数中创建了两个线程来模拟两个进程,一个线程执行producer的逻辑,一个线程执行comsumer的逻辑
int main()
{
	printf("Start a main function.");
	pthread_t thread1,thread1;
	pthread_create(&thread1, NULL, &producer, NULL);
	pthread_create(&thread1, NULL, &comsumer, NULL);
	pthread_join(thread1, NULL);
	pthread_join(thread2, NULL);
	printf("Print in main function: num = %d\n", num);
	retuen 0
}

Because the cycle times of the producer and the consumer are the same, the result of execution should be 0. Isn't the actual execution result? We will find that it is not, so this is the problem of producers and consumers. The buffer and num in the above example are critical resources

(2) The philosopher's meal problem

Problem description: There are five philosophers. Their lifestyle is to alternate thinking and eating. The philosophers share a round table and sit on the five chairs around. There are five bowls and five chopsticks on the round table. . Usually philosophers only think. When they are hungry, they try to take two chopsticks close to them. He can only eat when both chopsticks are held by him. After the meal, put down the chopsticks and continue thinking.
Insert picture description here

So why does this process need process synchronization? Imagine what happens when a philosopher has a meal. Suppose a philosopher is hungry at this time and he needs to pick up the chopsticks on the left and the chopsticks on the right to eat. At this time, the first step is to pick up the chopsticks on the left, and the second step is to pick up the chopsticks on the right. If he finds that the chopsticks on the right is taken at this time, then he will wait for the chopsticks on the right to be released . After the chopsticks are released, he Pick up the chopsticks on the right and start eating. This is the problem that philosophers may face when they eat. From this look, it seems that there is no problem.
Insert picture description here

Looking at an extreme situation, suppose these five philosophers are hungry at the same time and pick up the chopsticks on the left at the same time , and then they will find that all the chopsticks on their right have been taken (compare with the round table picture above. Click), then, at this time, the five philosophers will wait for the chopsticks on their right to be released. At this time, all the chopsticks are picked up by themselves, so they will wait for each other and cannot get the chopsticks, and neither of them Will release the chopsticks on his left, so these five philosophers will starve to death. This is the most extreme situation.

The above is the meal problem of philosophers. Now replace chopsticks with resources and philosophers with processes . This is the problem faced by computer processes. Chopsticks are critical resources .

Summarize what is the root cause of the above two problems?

  • The root cause of the problem is: no communication between each other
  • The first producer-consumer problem, we assume that the producer informs the consumer that I have completed a production
  • The second philosopher’s meal problem, suppose the philosopher tells the philosopher next to me that I want to eat, then there will be no problem

So draw the conclusion

Need inter-process synchronization , so what problem does inter-process synchronization solve?

1. Coordinating the order of using competing resources among multiple processes

2. Make the concurrent execution of multiple processes can effectively use resources and cooperate with each other

Two, the principle of synchronization between processes

Critical resources : Critical resources refer to shared resources that are shared resources but cannot be accessed by multiple processes or threads at the same time. When a process uses street resources, other processes must wait for the occupied process to release the shared resource according to the synchronization mechanism of the operating system before they can compete for the shared resource again

In order to effectively constrain critical resources , four principles of synchronization between processes are proposed

  • Idle letting in: resources are not occupied and allowed to be used
  • Waiting if busy: the resource is occupied and the requesting process is waiting
  • Limited waiting: guarantee that resources can be used for a limited waiting time and avoid other waiting processes from becoming dead
  • Give power to wait: When waiting, the process needs to give up the CPU, that is, the process changes from the execution state to the blocking state, which is also a prerequisite to ensure that the CPU can be used efficiently

Methods of synchronization between processes:
message queues, shared storage, semaphores. The method of synchronization between these processes will be described in detail in a later article

Three, thread synchronization

From the previous article "Process Entity of Process Management", we know that a process may have one or more threads, and threads share process resources. Now there is a question, what happens if multiple threads use process resources concurrently? In fact, there will also be the producer-consumer problem and the philosopher’s meal problem mentioned above, so we conclude that multithreading in the process also needs to be synchronized , because the threads in the process will concurrently use the shared resources in the process

Thread synchronization method :

  • Mutex: This is a lock that guarantees that multiple threads can mutually exclusive access critical resources
  • Read-write lock: This is a lock invented to deal with the situation of more reading and less writing or more writing and less reading
  • Spin lock
  • Condition variable

These methods will also be introduced in detail in a later article

It is the core competitiveness of a technical person to find the constant in the rapidly changing technology. Unity of knowledge and action, combining theory with practice
Insert picture description here

Guess you like

Origin blog.csdn.net/self_realian/article/details/106982942