Structure of a Program Using Lock Variables for Synchronization

The need for synchronisation

In a system that allows processes to communicate with each other, the operating system always needs to provide synchronization mechanisms to ensure that the operations of concurrent processes do not affect each other incorrectly for the following reasons:


Mutual exclusion


Maybe you are interested!

Resources in a system are divided into two types: sharable resources that allow multiple processes to access them simultaneously, and non-sharable resources that allow only one (or a limited number) of processes to use them at a time. Non-sharability of resources usually results from one of two reasons:


Structure of a Program Using Lock Variables for Synchronization

The hardware nature of the resource does not allow sharing.


If multiple processes use a resource concurrently, there is a risk of unpredictable results because the actions of the processes on the resource affect each other.


To solve the problem, it is necessary to ensure exclusive access to the resource, meaning that the system must control so that at a time, only one process is allowed to access a non-shareable resource.


Synchronization request


In general, the correlation between the execution speed of two processes in the system is unpredictable, because it depends on many dynamic factors such as the frequency of interrupts of each process, the time the process is allocated a processor, etc. It can be said that the processes operate asynchronously with each other. However, there are situations where the processes need to cooperate in completing a task, in which case it is necessary to synchronize the operations of the processes, for example, a process can only process if another process has finished a certain task, etc.


Synchronization problem


Race condition


Suppose there are two processes P 1 and P 2 that perform the work of accountants, and share a common memory area that stores the variable taikhoan that reflects information about an account. Each process wants to withdraw an amount of money tienrut from the account:


if (account - withdrawal >=0)

taikhoan = taikhoan - tienrut; else. else

error(« cannot make money! »);


Suppose there is 800 left in the account, P 1 wants to withdraw 500 and P 2 wants to withdraw 400. If the following situation occurs:


After checking the condition (account - advance >=0) and getting the result of 300, P 1 runs out of processing time allowed by the system, the operating system allocates CPU to P 2 .


P 2 checks the same condition above, gets the result of 400 (since P 1 has not withdrawn yet) and withdraws 400. The value of the account is updated to 400.


When P 1 is reactivated and continues processing, it will not recheck the condition (account

- tienrut >=0) - because it was checked in the previous processing - then withdraw money. The value of

The account will be updated to -100 again. Error occurred!


Similar situations - which can occur when more than two processes read and write data to the same shared memory area, and the outcome depends on the system's process coordination - are called race conditions .


critical section


To prevent error situations that can arise when processes access a non-shareable resource concurrently, it is necessary to impose an exclusive access on that resource: while one process is using the resource, other processes are not allowed to access the resource.


The part of the program where access conflicts on a common resource are likely to occur is called a critical section . In the above example, the code:


if (taikhoan - tienrut >=0) taikhoan = taikhoan - tienrut;

of each process forms a critical region.


The access conflict problem can be solved if it can be guaranteed that at any given time only one process is executing a command in the critical region.


A good method to solve the critical domain problem needs to satisfy the following four conditions:

No two processes can be in the critical region at the same time.


No assumptions are made about the speed of the processes, nor about the number of processors in the system.


A process paused outside the critical region must not prevent other processes from entering the critical region.


No process has to wait indefinitely to enter the critical region.


Summary


Some processes in the system need to exchange information to coordinate activities. Because each process has an independent address space, communication can only be done through mechanisms provided by the operating system.


Some mechanisms for information exchange between processes:


Signal : announces the occurrence of an event


Pipe : unstructured data transmission


Shared memory : allows multiple processes to access the same memory area


Message exchange : structured data transfer, can be applied in distributed systems


Socket : standardizes communication between different systems


When processes exchange information and share common resources, it is necessary to synchronize their activities mainly due to the need for exclusive access or coordination of activities.


A critical region is a section of code in a program that is likely to cause access conflicts. To avoid access conflicts, it is necessary to ensure that only one process can enter the critical region at a time.


Reinforce the lesson


Questions to be answered after this lesson:


1. Information exchange mechanisms: usage situations, advantages and disadvantages?


2. Synchronization requirements?

Exercise


Analyze the following problems and identify the synchronization requirements and critical regions:


Lesson 1. Problem of Creating H 2 O molecules


Synchronize the activities of a laboratory using the following co-processes to create H 2 O molecules :


MakeH() // Each MakeH process creates 1 H atom { Make-Hydro();}


MakeO() // Each MakeO process creates 1 O atom { Make-Oxy();}


MakeWater() /* The MakeWater process runs in parallel with the MakeH, MakeO processes, waiting for enough 2 H and 1 O to create H 2 O */{ while (T) Make-Water(); //Create 1 H 2 O molecule }


Lesson 2. The Old Bridge Problem


To avoid collapse, people only allow a maximum of 3 vehicles to pass through a very old bridge at the same time. Build the ArriveBridge(int direction) and ExitBridge() procedures to control traffic on the bridge so that:


At any one time, only a maximum of 3 vehicles are allowed on the bridge.


At any one time, only a maximum of 3 vehicles are allowed to travel in the same direction on the bridge.


Each vehicle when arriving at the bridge head will call ArriveBridge(direction) to check the bridge conditions, and when it has passed the bridge, it will call ExitBridge() to signal the end.


Suppose the operation of each car is described by the following Car() process :


Car(int direction) /* direction defines the direction of movement of each car.*/{


RuntoBridge(); // Go towards the bridge ArriveBridge(direction); PassBridge(); // Cross the bridge Exit Bridge(); RunfromBridge(); // Crossed the bridge


}


Lesson 3. Crossing the River Problem


To cross the river, Microsoft employees and Linux hackers use the same river dock and must share a number of special boats. Each boat can only carry one person.

4 people at a time, and there must be 4 people to start. To ensure safety for both sides, the following rules must be followed:


a. Don't put 3 Microsoft employees and 1 Linux hacker on the same boat.


b. Conversely, don't put 3 Linux hackers and 1 Microsoft employee on the same boat.


c. All other combinations are legal.


d. The boat will only depart when there are 4 passengers.


Need to build 2 procedures HackerArrives() and EmployeeArrives() which are called by a hacker or an employee respectively when they reach the river bank to check if the conditions allow them to get on the boat? These procedures will arrange the appropriate people to be able to get on the boat. Those who have been on the boat when the boat is not full will have to wait until the 4th person gets on the boat before they can start crossing the river. (Regardless of the number of boats or whether the boat crosses the river and returns… Assume there are always boats to arrange according to valid requests)


Suppose each hacker's activity is described by the following Hacker() process :


Hacker() {


RuntoRiver(); // Go to the river bank HackerArrives(); // Check the condition to get off the boatCrossRiver(); // Start crossing the river


}


and each employee's activity is described by the following Employee() process :


Employee() {


RuntoRiver(); // Go to the river bank EmployeeArrives(); // Check the condition to get off the boatCrossRiver(); // Start crossing the river


}


Lesson 4. Bus Passenger Coordination Problem


Imagine you are responsible for controlling passengers boarding a bus at a stop.

Each bus has enough space for 10 passengers. Of these, 4 seats are reserved for wheelchair users and the remaining 6 seats are reserved for regular passengers.


Your job is to let passengers board the bus according to the regulations, when the bus is full it will depart. There may be many buses and many passengers arriving at the station at the same time, the coordination principle is to put passengers on a bus, let this bus depart and then coordinate to another bus.


Suppose your passenger scheduling for a bus is described by the GetPassengers() process ; the activities of each passenger depending on the type are described by the following WheelPassenger() and NonWheelPassenger() processes, respectively . Modify the code, using the semaphore mechanism to implement the necessary synchronization principles.


GetPassenger() {


ArriveTerminal(); // receive a vehicle at the stationOpenDoor(); // open the vehicle door, this procedure is considered to existfor (int i=0; i<4; i++) // receive passengers in wheelchairs{ ArrangeSeat();

// seat a guest


}


for (int i=0; i<6; i++) // receive normal passengers { ArrangeSeat(); // put 1 passenger in a seat


}


CloseDoor(); // close the car door, this procedure is considered to have DepartTerminal(); // let a car leave the station

}


WheelPassenger() {


ArriveTerminal(); // arrive at the stopGetOnBus(); // get on the bus


}


NonWheelPassenger() {


ArriveTerminal(); // arrive at the stopGetOnBus(); // get on the bus


}


Lesson 5. Car equipment manufacturing problem

Pontiac has two parallel operating divisions:


- Production department of 1 car frame:


MakeChassis() { // create chassis Produce_chassis();


}


- Production department of 1 wheel:


MakeTires() { // create the wheel and attach it to the chassis Produce_tire(); Put_tire_to_Chassis();


}


Synchronize activities in car production according to the following principles: 1: Produce a car frame,

2: 4 wheels are needed for a frame to be produced, then another frame can be produced...

Synchronization solutions

This lesson will introduce specific solutions to the synchronization problem. There are many solutions to implement critical region access, which are divided into two classes depending on the approach in handling the blocked process: « busy waiting » solutions and « sleep and wakeup » solutions.


Solution « busy waiting »


Software solutions


Using flag variables:


Continuity : processes share a common variable called a “lock” that is initialized to 0. A process that wants to enter the critical section must first check the value of the variable lock. If lock = 0, the process resets lock to 1 and enters the critical section. If lock is holding the value 1, the process must wait outside the critical section until lock has the value 0. Thus, a lock value of 0 means that no process is in the critical section, and lock=1 when a process is in the critical section.


while (TRUE) {


while (lock == 1); // waitlock = 1; critical-section(); lock = 0 ; Noncritical-section();


}


Figure 3.5 Structure of a program using lock variables for synchronization


Discuss: This solution may violate the first condition: two processes can be in the critical region at the same time. Suppose a process finds that lock = 0 and prepares to enter the critical region, but before it can reset lock to 1, it is paused to allow another process to execute. This second process finds that lock is still 0, enters the critical region and resets lock = 1. Then the first process is reactivated, it sets lock = 1 again and enters the critical region. Thus at that moment both processes are in the critical region.


Use rotation testing:


Approach : Here is a proposed solution for two processes. The two processes share a common variable turn (reflecting which process session is allowed to enter the critical region), which is initialized with the value 0. If turn = 0 , process A enters the critical region. If turn = 1 , process A

Comment


Agree Privacy Policy *