# Operating system on November 22, 2021 (semaphore solving some problems + deadlock)

Keywords: hardware

# 5. Dining problem of philosophers

There may be two critical resources required by a process that are available but not available and then blocked, or a process may only get one critical resource and then be blocked

# 5. Tube side

## 7.4 failure cycle waiting conditions

After the process has applied for a large number of critical resources, it can no longer apply for a small number of critical resources, breaking the dead chain of the process application resource cycle

## 8.1 safety sequence

The banker algorithm can be used more easily in practical calculation

# summary

1. Talk about the synchronization problem you know about the application of semaphore mechanism?

Producer consumer issues

```//Mutual exclusion should be attached to the access to critical resources, otherwise deadlock will occur
//The code segments of producers and consumers that do not involve the operation of critical resources are written outside the PV operation, so as to improve the concurrency of the process

semaphore mutex = 1;
semaphore empty = n;
semaphore full = 0;

public void Producer(){
while(1)
{
Produce a product;
P(empty);
P(mutex);
Put product into buffer;
V(mutex);
V(full);
}
}

public void Consumer(){
while(1)
{
P(full);
P(mutex);
Take the product out of the buffer;
V(mutex);
V(empty);
Consume a product;
}
}```

Multi producer multi consumer problem

```// The reason why mutex is not set here is that the critical resource size is 1, so two or more processes will not access the critical resource
// Note that only one Plate is set for the semaphore type variable here, because after the son and daughter access the critical resources, the father and mother can start giving birth.

semaphore apple = 0;
semaphore banana = 0;
semaphore plate = 1;

while(1){
peel an apple;
P(plate);
Put the apple on the plate;
V(apple);
}
}

public void Mom(){
while(1){
Peel bananas;
P(plate);
Put the bananas on the plate;
V(banana);
}
}

public void Son(){
while(1){
P(apple);
Take the apple out of the plate;
V(plate);
Eat apples
}
}

public void daughter(){
while(1){
P(banana);
Take out the bananas from the plate;
V(plate);
Eat bananas;
}
}```

Smoker Problem

```semaphore offer1 = 0;
semaphore offer2 = 0;
semaphore offer3 = 0;
semaphore ashtray = 1;
int i = 0;

public void offer(){
if(i == 0){
production offer1;
P(ashtray);
take offer1 Put in the ashtray;
V(offer1);
}
else if(i == 1){
production offer2;
P(ashtray);
take offer2 Put in the ashtray;
V(offer2);
}
else if(i == 2){
production offer3;
P(ashtray);
take offer3 Put in the ashtray;
V(offer3);
}

i = (i+1)%3;
}

public void smoker1(){
P(offer1);
Take it out of the ashtray offer1;
V(ashtray);
use offer1;
}

public void smoker2(){
P(offer2);
Take it out of the ashtray offer2;
V(ashtray);
use offer2;
}

public void smoker3(){
P(offer3);
Take it out of the ashtray offer3;
V(ashtray);
use offer3;
}```