Process Synchronization-Classic synchronization issues

Source: Internet
Author: User
Tags mutex semaphore

This article for Bo Master original article, without BO Master permission cannot reprint http://www.cnblogs.com/kiplove/p/6724431.html

Some concepts that involve process synchronization:

Mutex and synchronization:

Critical resource (critical section): A shared resource that can only be used by one process at a time is called a critical resource;

Synchronization: Refers to the two and many processes established to accomplish a certain task, which in the process of co-operation needs to coordinate the orderly access of the work order and the constraints arising from waiting.

Mutual exclusion: When two or more processes access critical resources, only one process accesses, and the other processes wait for a mutually restrictive relationship.

Semaphore and Mutex:

Semaphore: itself is a counter, using p,v two operations to achieve the subtraction and addition of the count, when the count is not more than 0 o'clock, then the process goes to sleep, it is used to provide access to the shared data objects for multiple processes.

Mutex: If the semaphore only has two states, then it does not need to be counted, can be simplified to locking and unlock two functions, this is the mutex amount.

I. Producer and consumer issues

Problem Description: A set of producer processes and a group of consumer processes share a block of initially empty, size-determined buffers, only when the buffer is full, the producer process can put the information into the buffer, otherwise it will wait; only if the buffer is not empty, the consumer process can take out the message, otherwise it will wait. The buffer can only be accessed one process at a time (critical resource).

Problem Analysis: The producer and consumer process access to the buffer is mutually exclusive, and the producer and the consumer itself has a synchronous relationship, that must be generated before consumption. Thus, for the access of the buffer set a mutex, and then set two semaphores a record of the free buffer unit, a record full buffer unit to achieve the producer and consumer synchronization.

Problem solving: pseudo-code implementation

Semaphore mutex=1; semaphorefull =0;         // Full buffer unit semaphore empty=n;    // Free buffer Unit Prodecer () {    while(1)    {          P (empty);                    P (mutex);          Add_source+ +;          V (mutex);          V (full);          }    }        Consumer () {    while(1)   {         P (full);         P (mutex);         Add_source--;         V (mutex);         V (empty);         }    }

Ii. Reader and writer questions

Problem Description: There are readers and two concurrent processes to share one data, two or more read processes can access the data, but a writer process access to data and other processes are mutually exclusive.

Problem analysis: The reader and writer are mutually exclusive relations, the writer and writer are mutually exclusive relations, readers and readers are synchronous relations. Thus a mutex is required to achieve read and write and write and write mutexes, a reader's access count and the implementation of mutual exclusion of the count.

Problem solving: Three kinds of pseudo-code implementations

1, the reader first

Readers first, as long as there is a steady stream of readers, the writer will not have the resources. Easily cause the writer to starve.

1 //Readers First2 3 intCount=0;4Semaphore mutex=1;//Reader Count Lock5Semaphore rw=1;//Resource access Lock6 7 writer ()8 {9      while(1)Ten     { One P (rw); A writing sth; - V (rw); -     } the } -  - Reader () - { +      while(1) -     { + P (mutex); A         if(count==0) at P (rw); -count++; - V (mutex); - reading sth; - P (mutex); -count--; in         if(count==0) - V (rw); to V (mutex); +     } -}

2. Fair reading and writing

The reader and the writer are fair to seize the resources, but as long as the readers who have queued before, even if the writer gets the resources, also waits for all the waiting reader process to end.

1 //Read and Write fairness2 intCount=0;3Semaphore mutex=1;//Reader Count Lock4Semaphore rw=1;//Resource access Lock5Semaphore w=1;//read-write fair preemption lock6 writer ()7 {8      while(1)9     {Ten P (w); One P (rw); A writing sth; - V (rw); - V (w); the     } - } -  - Reader () + { -      while(1) +     { A P (w); at P (mutex); -         if(count==0) - P (rw); -count++; - V (mutex); - V (w); in reading sth; - P (mutex); tocount--; +         if(count==0) - V (rw); the V (mutex);  *     } $}

3, written by priority

Writing is a priority, as long as the writer is a constant stream, the reader will not get the resources, but in the queue before the reader process can still give priority to access to resources, after which is waiting for the end of all the writer process. This also easily causes the reader to starve.

1 //written by Priority2 intWrite_count=0;//Write Count3 intCount=0;//Read Count4Semaphore w_mutex=1;//Lock when reading Count5Semaphore r_mutex=1;//Lock when writing count6Semaphore rw=1;//Write priority Lock7Semaphore source=1;//Resource access Lock8 9 writer ()Ten { One      while(1) A     { - P (W_mutux); -         if(write_count==0) theP (rw);//the acquisition will not be released as long as the write process comes in . -write_count++; - V (W_mutux) -      +P (resouce);//write-time mutex must be a resource exclusive lock - writing sth; + V (resouce); A          at P (W_mutux); -write_count--; -         if(write_count==0) - V (rw); - V (W_mutux); -     } in } -  to Reader () + { -      while(1) the     { *P (rw);//use the immediate release $ P (R_mutex);Panax Notoginseng         if(count==0) - P (resouce); thecount++; + V (R_mutex); A V (rw); the      + reading sth; -          $ P (R_mutex); $count--; -         if(count==0) - V (resouce); the V (R_mutex);  -     }Wuyi}

Third, the question of dining philosophers

Description: A table of five philosophers, each of the two philosophers between the tables placed a chopstick, philosophers only at the same time to pick up the left and right two chopsticks to eat, eat the chopsticks put back in place.

Problem Analysis: Here five philosophers are five processes, and five chopsticks are the resources to be acquired. You can define a mutex array to represent mutually exclusive access to five chopsticks, in order to prevent the philosopher from taking a single chopstick deadlock, you need to add some restrictions. One way is to restrict the use of chopsticks only when the philosopher is around to pick up chopsticks, where a mutex is needed to restrict access to chopsticks without competition.

Problem solving: Only one philosopher can pick up chopsticks at a time, which is less efficient.

1Semaphore chopstick[5]={1,1,1,1,1};2Semaphore mutex=1;3 Pi ()4 {5      while(1)6     {7 P (mutex);8 P (Chopstick[i]);9P (chopstick[(i+1)%5]);Ten V (mutex); One          A eating; -          - V (Chopstick[i]); theV (chopstick[(i+1)%5]); -     } -}

Supplemental content

Deadlock: If each process in a process collection waits for an event that can only be raised by another process in the process collection, the process collection is deadlocked.

Deadlock conditions (four simultaneous gratification):

(1) Mutual exclusion: each resource is either already assigned to a process or is available;

(2) Possession and waiting: the process of a given resource has requested new resources;

(3) Not preemption: The allocated resources can not be forced to be preempted, only the process of their own display of the release;

(4) Loop wait: There is a cyclic wait chain for a process resource.

Deadlock handling Policy:

(1) Deadlock prevention: one of the four conditions that destroys a deadlock

Broken-loop Mutex condition: Allow resource sharing

Broken ring occupancy and wait conditions: pre-static allocation

No preemption: When a new resource is requested, release the resources that have been held in place and reapply later

Loop wait: Using sequential resource allocation method

(2) Deadlock avoidance: Deadlocks Avoid pre-prevention strategies, but are used in the process of dynamic allocation of resources to prevent the system from entering an unsafe state to avoid deadlocks.

Banker algorithm: Use resource vector available to request vector requests

Max demand matrix max, allocation matrix allocation, demand matrix need

Get the number of resources required for each process by need=max-allocation need matrix

Typically each process request vector should be less than or equal to the value of need

Temptation Assignment: Available=avaliable-request

Allocate corresponds to an item =allocate the corresponding item +request

Need corresponds to an item =need the corresponding item-request

Security algorithm: Check the resource allocation, whether the system is a security state, if security is formally allocated resources, otherwise void. A security sequence (core) is generally calculated from a security algorithm.

(3) Deadlock detection and cancellation:

Detecting deadlocks: Detecting the existence of deadlocks by using the deadlock-based simplified resource allocation graph

Deadlock Cancellation: Resource deprivation, revocation process, process fallback

Process Synchronization-Classic synchronization issues

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.