Process Synchronization in the operating system

Source: Internet
Author: User

Process Synchronization
As mentioned above, the collaboration process affects other processes, that is, it shares the logical address space, that is, the shared memory system. In this case, it is very likely that an error will occur when accessing the same variable at the same time. There is also an independent process that will not be affected. The messaging collaboration process does not cause synchronization issues.

Therefore, this chapter discusses the shared memory-based collaboration process.

// Producer-consumer solution <br/> // producer <br/> while (true) <br/> {<br/> while (counter = buffer_size ); <br/> buffer [in] = nextproduced; <br/> In = (in + 1) % buffer_size; <br/> counter ++; <br/>}< br/> // ---------------------------- <br/> // consumer <br/> while (true) <br/>{< br/> while (counter = 0); <br/> nextconsumed = buffer [out]; <br/> out = (out + 1) % buffer_size; <br/> counter --; <br/>}
Competition condition: the result of concurrent access to the same data cut by multiple processes is related to the execution process.
Critical section: Only one process can be executed in the critical section.
Processes can be divided into the entry area, critical area, exit area, and remaining area. The code for entering the critical section is required, and the Code for exiting the critical section is required.
Critical Zone problem: Enter when there is no blank, wait for a limited amount.

In the operating system, the execution of kernel code also encounters a critical section problem.
The kernel code can be preemptible or non-preemptible.
Non-preemptible kernel: after a process enters the kernel mode, it is not allowed to access another process. Therefore, it will not lead to competition conditions.

Preemptible kernel data inconsistency occurs because the processes allowed to be executed in the kernel are preemptible.

It is more difficult to control SMP structures because processes are on different processors.

Peterson algorithm: used to deal with critical zone issues. The goal of the Peterson algorithm is to "humble", because at the beginning, we leave the opportunity to another person.
Do
{
Flag [I] = true;
Turn = J;
While (flag [J] & turn = J );
...
Flag [I] = false;
} While (true );

Flag indicates that you want to enter the critical section, and turn indicates that you can enter the critical section.

We will talk about hardware synchronization through software.
For a single processor, interruption must be disabled when the shared variable is modified, so that the kernel is not preemptible.

For multi-processor, it is not feasible to use the previous notification to prohibit interruption, because it is slow to send the prohibition interruption to all processors. Therefore, a machine command can be executed atomically.
Atomic location: it cannot be interrupted.

The example of testandset in the book is too sudden to get started, so I checked the information and started talking about it gradually.

Do {

While (turn! = I );

Critical Section

Turn = J;

Remaining Zone

} While (true );

The problem in this example is that in the exit area, turn = J is too abrupt, because it does not meet the principle of entering when there is no time. If J does not enter, no one can enter it.

The following example adds the bool variable.

Do {

Flag [I] = true;

While (flag [J]); // The problem is that if flag [J] does not go in and is still waiting, I will never be able to enter, so it does not solve the condition of being free.

Critical Section

Flag [I] = false;

Remaining Zone

} While (true );

Bool testandset (bool * target)
{
Bool * r = * target;
* Target = true;
Return R;
}
Do
{
While (testandset (& lock ));
...
Lock = false;
} While (true );
Analysis: when starting, the lock is false. If false is returned, the system enters the critical section because no lock is applied. If the lock is true, it means that someone is in the critical section and cannot enter.

Disadvantage: it can solve mutual exclusion and forward. But there is no solution to the limited wait.

Void swap (bool * a, bool * B)
{
Bool temp = *;
* A = * B;
* B = temp;
}
Do
{
Key = true;
While (Key = true)
Swap (& Key, & lock );
...
Lock = false;
 
} While (true );
Analysis: Start lock is false, key is true, because there is no one in the critical section at the beginning, so after the key is switched to false, it enters the critical section.

In fact, the above two ideas are the same. If the lock is false at the beginning, the loop will jump out. However, they cannot meet the limited waiting condition, because there is no definition for multi-process to indicate when to enter the critical section. The disadvantage is the same as above.

// The following implement a limited wait because it will be viewed in a round like a cyclic queue. If waiting [J] = true and J! = I: When J is waiting, waiting [J] = false; if J = I, lock = false;

-----------------------

Do
{
Waiting [I] = true;
Key = true;
While (waiting [I] & Key)
Key = testandset (& lock );
Waiting [I] = false;
....
J = (I + 1) % N;
While (J! = I &&! Waiting [J])
J = (J + 1) % N;
If (j = I)
Lock = false;
Else
Waiting [J] = false;
} While (true );

Semaphores (that is, the number of resources expressed by the integer size) can be used for synchronization. The semaphores are defined as s, indicating the number of resources they own. There is an atomic operation of wait (s ), signal (s) indicates -- and ++.

Semaphores include count semaphores and binary semaphores.
When a process needs to use resources, wait is called.
However, semaphores have the disadvantage of being busy. Busy means that when a process enters the critical section, other processes must keep repeating in the while loop and can only enter when a process exits the critical section. CPU time is wasted, so the solution is that when a process enters the critical section, you can use the spin lock to make other processes enter other critical sections and make full use of the CPU time.
When the resources are used up, the wait function puts the process into the waiting queue and uses CPU scheduling to call another process.

To determine the order in which two processes access specific data
P1
Signal (s );
-------------------

P2

Wait (s );
-------------------

If S is initialized to 0, P1 must be executed first.

The disadvantage of semaphores is that busy waiting (but may also be advantageous because context switching may consume more resources) is caused by Wait operations. This is called a spin lock because it is always spinning...
The spin lock solution is that when process a calls wait, if the resources are used up, it will block the waiting queue that enters the semaphore. If there is another resource in signal, then, wakeup wakes him up and enters the ready queue in the memory.

Struct semaphore

{

Int value;

Struct process * List; // wait for the queue. Signal fetches a process from the wait queue to wake up.

};

Wait (semaphore * s)

{

S-> value --;

If (S-> value <0 ){

Block (); // enter the waiting queue and call it again

}

}

Signal (semaphore * s)

{

S-> value ++;

If (S-> value> 0 ){

Wakeup (p); // wake up a process from the waiting queue

}

}

Multi-processor can use spin locks for synchronization, that is, a process runs on one processor, and a process spin on another processor.

Only one PV operation is required! That is, wait and signal must be atomic.

In single-processor and multi-processor (SMP), interruption is prohibited to solve the atom.

Deadlock: multiple processes may cause deadlocks on semaphores. A deadlock means that the process must wait for the signal (s) of the B Process for the wait (s) semaphores, and the B process is for the wait (t) wait for process a signal (T), and both parties are in a deadlock state.

The LIFO implementation method of the semaphore wait queue may cause infinite blocking or hunger. That is, it cannot be executed.

 

Typical synchronization problems:

1. Limited Buffer: producer and consumer issues

// Empty is the number of empty buffer, and full is the number of full buffer. mutex is the mutex lock.

// Producer
Do
{
// Produce
Wait (empty );
Wait (mutex );
 
Signal (mutex );
Signal (full );
} While (true );
// Consumer
Do
{
Wait (full );
Wait (mutex );
 
Signal (mutex );
Signal (empty );
} While (true );
2. Reader issues

The requirement of readers is that there can be multiple readers and one writer.
Readers have questions about the first reader and the second reader.
First reader writer problem: the reader does not need to wait unless a writer has entered the critical section.
Second reader writer problem: Once the writer starts to wait, the writer will perform the write operation as quickly as possible, and the read operation cannot take the lead.
// Known mutex, WRT are binary semaphores, initialized to 1, readcount is the number of readers
// Writer
Do
{
Wait (WRT );
Critical Section
Signal (WRT );
} While (true );

// Reader
Do
{
Wait (mutex );
Readcount ++;
If (readcount = 1)
Wait (WRT );
Signal (mutex );
 
Wait (mutex );
Readcount --;
If (readcount = 0)
Signal (WRT );
Signal (mutex );
} While (true );

Of course, for example, Java provides read/write locks, which can facilitate Process Synchronization and solve the writer's problem, but the overhead is high.
3. Dining by philosophers

Semaphore chopstick [5];
Do
{
Wait (chopstick [I]);
Wait (chopstick [(I + 1) % 5]);
// Eat
Signal (chopstick [I]);
Signal (chopstick [(I + 1) % 5]);
// Think
} While (true );
This method causes a deadlock because when philosophers execute the first statement, they cannot execute the next statement. Discard.

Solution:
1. A maximum of four philosophers can sit on the table at the same time ..
2. Only two chopsticks can be picked up.
3. The odd philosophers first take the chopsticks on the left and then the chopsticks on the right, while the even philosophers take the opposite.

 

Semaphores are not safe enough because they may be written incorrectly. Therefore, monitor is introduced ).

By default, only one process can be active in the management process, so you do not need to write synchronization code manually.

You can define additional synchronization mechanisms for variable of the condition type. Only wait and signal operations are performed on condition variables.

Wait only means the process block, and signal only means restarting the process. The condition variable is similar to a semaphore and has a waiting queue. Used to suspend a process.

Realization of the dining problem of philosophers Based on Guan Cheng:

Monitor DP
{
Enum {thinking, hungry, eating} State [5];
Condition self [5];
 
Void pickup (int I)
{
State [I] = hungry;
Test (I );
If (State [I]! = Eating)
Self. Wait ();
}
 
Void putdown (int I)
{
State [I] = thinking;
Test (I + 4) % 5 );
Test (I + 1) % 5 );
}

Void test (int I)
{
If (State [(I + 4) % 5]! = Eating) & State [I] = hungry & State [(I + 1) % 5]! = Eating)
{
State [I] = eating;
Self [I]. Signal ();
}
}

Initialization_code () // initialization code, which must be
{
For (INT I = 0; I <5; I ++)
State [I] = thinking;
}
}

// Remember: the operations of a manager are mutually exclusive by default.

The problem discussed below is the selection method of the condition variable waiting for the queue to restart the process.

Conditional queues are usually used. The priority is set as follows:

The process first specifies the maximum requirement for resource allocation.

You must pay attention to the correct use of advanced management operations.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.