BASIC PRINCIPLES OF SYNCHRONISATION. MAIN CONCEPTS SYNCHRONISATION CRITICAL SECTION DEAD LOCK.
-
date post
19-Dec-2015 -
Category
Documents
-
view
256 -
download
7
Transcript of BASIC PRINCIPLES OF SYNCHRONISATION. MAIN CONCEPTS SYNCHRONISATION CRITICAL SECTION DEAD LOCK.
MAIN CONCEPTSMAIN CONCEPTS
SYNCHRONISATIONSYNCHRONISATION
CRITICAL SECTIONCRITICAL SECTION
DEAD LOCKDEAD LOCK
Multiprogramming created an environment for concurrent Multiprogramming created an environment for concurrent classic processes.it also made available for a programmer to classic processes.it also made available for a programmer to create a group of cooperating processes to work create a group of cooperating processes to work concurrently on a single problem.concurrently on a single problem.
how ever,multiple cooperating processes/threads introduce how ever,multiple cooperating processes/threads introduce the potential for new synchronisation problems in software the potential for new synchronisation problems in software implementations such as: implementations such as:
dead lockdead lock
critical sectioncritical section
non deteminacynon deteminacy
What is synchronisationWhat is synchronisation
SynchronisationSynchronisation
it refers to the act of ensuring that independent it refers to the act of ensuring that independent processes/threads begins to execute a designated block of processes/threads begins to execute a designated block of code at the same logical timecode at the same logical time
Suppose a team has a plan for attacking a fort in which, Suppose a team has a plan for attacking a fort in which, each member of the team must be prepared to perform a each member of the team must be prepared to perform a specific task at exactly same time thenspecific task at exactly same time then
1.they must perform their actions at almost1.they must perform their actions at almost exactly at the same timeexactly at the same time 2.they must synchronize their watches by setting same 2.they must synchronize their watches by setting same
timetime
How syncronisation manifests itself inHow syncronisation manifests itself in concurrent software concurrent software
Enter loop
ANOTHER COMMAND ?ANOTHER COMMAND
EXIT LOOPEXIT LOOP
EXCUTE COMMAND EXCUTE COMMAND
EXCUTE COMMAND
WAIT FOR CHAILD TO TERMINATE
YESYES
NONO
FORK() CODE CREATEPROCESS () CODE
Unix shell Windows command launch
programprogram
UNIXUNIX
While (TRUE){While (TRUE){……//create a process to execute //create a process to execute
the commandthe command if((chPID =fork()) ==0) {if((chPID =fork()) ==0) {//this is the child//this is the childExecv(command.name,commExecv(command.name,comm
and.argv);and.argv);}}//wait for the child to //wait for the child to
terminateterminatethisChPID =wait(&stat);thisChPID =wait(&stat);}}
WindowsWindowsWhile While
fgets(cmdline,MAX_LINE_LEfgets(cmdline,MAX_LINE_LEN,FID)!NULL){N,FID)!NULL){
//b.create a new process to //b.create a new process to execute the commandexecute the command
If(!create a new process to If(!create a new process to execute the commandexecute the command
If (!If (!createprocess(Null,cmdline,.createprocess(Null,cmdline,..).)
{/* error handling code…*/}{/* error handling code…*/}
}}
unixunix Parent program creates a child process to execute a Parent program creates a child process to execute a
command ,then waits for the child to terminate before command ,then waits for the child to terminate before reading next command.reading next command.
When this program processes 5 commands ,then the When this program processes 5 commands ,then the processes that execute the commands will be created processes that execute the commands will be created sequentially.sequentially.
Concurrency between the parent and atmost one child at a Concurrency between the parent and atmost one child at a time.time.
windowswindows The parent process creates a process to execute a The parent process creates a process to execute a
command ,then immediately goes back to the top of the command ,then immediately goes back to the top of the loop to create another process to execute another commandloop to create another process to execute another command
There is concurrency among the parent and all of the child There is concurrency among the parent and all of the child processesprocesses
Synchronizing multiple threads with Synchronizing multiple threads with shared variableshared variable
initializeinitialize
createThread(…)createThread(…)
Wait Wait runTime runTime secondsseconds
ThreadThread
WorkWork
exitexit terminateterminate
FALSEFALSE FALSEFALSE FALSEFALSE
runFlag ?runFlag ?runFlag ?runFlag ?runFlag ?runFlag ?
truetrue truetruetruetrue
Multiple threadsMultiple threads
Parent thread creates N child threads,each Parent thread creates N child threads,each running as an iterative loop.running as an iterative loop.
At the end of the loop,each child checks to see if At the end of the loop,each child checks to see if the RUN FLAG has been set FALSE, if not child the RUN FLAG has been set FALSE, if not child iterates through the loop again.iterates through the loop again.
If the RUN FLAG has been set FALSE,then the If the RUN FLAG has been set FALSE,then the child terminateschild terminates
Program for multiple threadsProgram for multiple threadsStatic int runFlag =TRUEStatic int runFlag =TRUEVoid main(…{Void main(…{ … …//for 1 to n//for 1 to nFor (i=0;i<n;i++) {For (i=0;i<n;i++) {//create a new thread to executes simulated work//create a new thread to executes simulated work createThread(…);createThread(…);}}//runtime is the number of seconds that the children should run//runtime is the number of seconds that the children should run//sleep while children work…//sleep while children work…Sleep(runtime*1000);Sleep(runtime*1000);RunFlag =FALSE;RunFlag =FALSE;……}}
Sleep(k) causes the thread to sleep for k milliseconds.Sleep(k) causes the thread to sleep for k milliseconds.
While the child threads work for run time seconds ,the parent While the child threads work for run time seconds ,the parent thread sleepsthread sleeps
CRITICAL SECTIONCRITICAL SECTION
Intersection is shared between two Intersection is shared between two streetsstreets
In software ,there may be certain parts of the two processes In software ,there may be certain parts of the two processes that should not be executed concurrently.such parts of the that should not be executed concurrently.such parts of the code are the software critical sections.code are the software critical sections.
PROGRAMPROGRAM shared double balance; /* shared variable*/shared double balance; /* shared variable*/Code schema for p1 Code schema for p2Code schema for p1 Code schema for p2……. ……. ……Balance = balance+amount; Balance=balance-amount;Balance = balance+amount; Balance=balance-amount;…….. ……... …….This is a critical sectionThis is a critical section
Code schema for p1 code schema for p2Code schema for p1 code schema for p2
Load R1,balance load R1,balanceLoad R1,balance load R1,balanceLoad R2,amount load R2,amountLoad R2,amount load R2,amountAdd R1,R2 sub R1,R2 Add R1,R2 sub R1,R2 Store R1,balance store R1,balance Store R1,balance store R1,balance
Critical sectionCritical section
execution of p1 execution of p2execution of p1 execution of p2 …… …… load R1,balanceload R1,balance load R2,amountload R2,amount timer interrupttimer interrupt
… …. . load R1,balanceload R1,balance load R2,amountload R2,amount sub R1,R2sub R1,R2 store R1,balancestore R1,balance …… ……
add R1,R2add R1,R2 store R1, balancestore R1, balance … …....
the problem occurs because of sharing ,not because of error in the problem occurs because of sharing ,not because of error in the sequential codethe sequential code
Timer interrupt
How to avoid critical sectionHow to avoid critical section One way of avoiding critical section problem in One way of avoiding critical section problem in
the program above discussed is by using the program above discussed is by using interrupts.interrupts.
Now we are going to use TRAFFIC LIGHTS at the Now we are going to use TRAFFIC LIGHTS at the intersection,those are the interrupts intersection,those are the interrupts
1.enable interrupts1.enable interrupts
2.disable interrupts2.disable interrupts
The program will DISABLE interrupts when it The program will DISABLE interrupts when it entered a critical section and then enable when it entered a critical section and then enable when it finished the critical sectionfinished the critical section
Program using interruptsProgram using interrupts Shared double amount,balance; /*shared variables*/Shared double amount,balance; /*shared variables*/
Program for p1 program for p2Program for p1 program for p2
disableInterrupts(); disableInterrupts(); disableInterrupts(); disableInterrupts(); Balance=balance+amount; balance=balance- amount;Balance=balance+amount; balance=balance- amount; enableInterrupts(); enableInterrupts(); enableInterrupts(); enableInterrupts();
Suppose a program contained an infinite loop inside its critical Suppose a program contained an infinite loop inside its critical section .the interrupts would be permanently disabled.USER MODE section .the interrupts would be permanently disabled.USER MODE programs cannot invoke enableInterrupt() and disable interrupt().programs cannot invoke enableInterrupt() and disable interrupt().
Now we have to find solution which interrupts are not used by which Now we have to find solution which interrupts are not used by which we can avoid long or infinite compute intervals. And to make the we can avoid long or infinite compute intervals. And to make the two threads coorinate.two threads coorinate.
Program using a lockProgram using a lock In order to coordinate their processes between p1,p2. SHARED FLAG, In order to coordinate their processes between p1,p2. SHARED FLAG,
LOCK is used instead of Interrupts .LOCK is used instead of Interrupts . shared boolean lock = false; /shared variables*/shared boolean lock = false; /shared variables*/ shared double amount ,balance /*shared variables*/shared double amount ,balance /*shared variables*/ program for p1 program for p2program for p1 program for p2 …… ……. ……... …….. /*Acquire lock */ /*Acquire lock*//*Acquire lock */ /*Acquire lock*/ while (lock) {null;}; while(lock) {null;};while (lock) {null;}; while(lock) {null;}; lock = TRUE; lock =TRUE;lock = TRUE; lock =TRUE;
/*execute crit section */ /*execute crit section *//*execute crit section */ /*execute crit section */ balance = balance+amount; balance = balance_amount;balance = balance+amount; balance = balance_amount;
/*release lock */ /*release lock*//*release lock */ /*release lock*/ lock = FALSE lock = FALSE;lock = FALSE lock = FALSE; …… ……. ……. . …….
Suppose p1 is interrrupted during the execution Suppose p1 is interrrupted during the execution of the statement of the statement
balance = balance +amount;balance = balance +amount;
after having set lock to TRUE.after having set lock to TRUE.
P2 then begins to execute . p2 will wait to obtain P2 then begins to execute . p2 will wait to obtain the lock at its while statement. Here clock the lock at its while statement. Here clock interrupts p2 and resumes p1.which can complete interrupts p2 and resumes p1.which can complete CRITICAL SECTION.CRITICAL SECTION.
The entire time slice is spent executing WHILE The entire time slice is spent executing WHILE stament. stament.
The execution pattern
P2 EXECUTION
P1 EXECUTION
lock
= T
RU
E
inte
rrupt
inte
rrupt
Lock
=FA
LSE
inte
rrupt
BLOCKED AT WHILE
The problem is that manipulating the lock variable is ,itself The problem is that manipulating the lock variable is ,itself critical section critical section
U have to solve small critical section problem before solving U have to solve small critical section problem before solving the original one the original one
The lock critical section will be exactly the same code every The lock critical section will be exactly the same code every time a process wants to enter a critical section time a process wants to enter a critical section
Using this knowledge, we recognize that it would generally Using this knowledge, we recognize that it would generally be acceptable to disable interrupts while we test and set be acceptable to disable interrupts while we test and set the lock variable , since it will only 3-4 machine the lock variable , since it will only 3-4 machine instructions.instructions.
Since enable interrupts and disable interrupts are Since enable interrupts and disable interrupts are privileged ,we can define two new operating privileged ,we can define two new operating system callssystem calls
1. enter()1. enter() 2. exit()2. exit()
In this case interrupts are disabled only by In this case interrupts are disabled only by operating system code (while lock is being operating system code (while lock is being manipulated )manipulated )
Even when a process is blocked , waiting to enter Even when a process is blocked , waiting to enter its critical section, the interrupts are only disabled its critical section, the interrupts are only disabled for a few instructions at a time for a few instructions at a time
It will never be delayed for more than the time It will never be delayed for more than the time taken to execute the while statement taken to execute the while statement
enter (lock){ exit(lock) { enter (lock){ exit(lock) {
disableInterrupts(); disableInterrupts(); disableInterrupts();disableInterrupts();
/* wait for lock */ lock=FALSE; /* wait for lock */ lock=FALSE;
while (lock)\while (lock)\{ enableInterrupts();{ enableInterrupts();
/* let interrupt occur *//* let interrupt occur */
enableInterrupts();enableInterrupts();
disableInterrupts(); }disableInterrupts(); }
lock=TRUE;lock=TRUE;
enableInterrupts();enableInterrupts();
}}
Lock manipulation as a critical Lock manipulation as a critical sectionsection
The same program using enter() and exit() functions The same program using enter() and exit() functions
shared double amount , balance; /* shared variables */shared double amount , balance; /* shared variables */
shared int lock = FALSE; /* synchronization variable */shared int lock = FALSE; /* synchronization variable */
program for p1 program for p2program for p1 program for p2
enter (lock); enter (lock);enter (lock); enter (lock);
balance= balance + amount; balance= balance – balance= balance + amount; balance= balance – amount;amount;
exit (lock); exit (lock); exit (lock); exit (lock);
Dead lockDead lock
The existence of critical sections creates an The existence of critical sections creates an environment in which a new , subtle problem can environment in which a new , subtle problem can occur : DEAD LOCKoccur : DEAD LOCK
In software , dead locks occur because one In software , dead locks occur because one process holds resource (such as file A) while process holds resource (such as file A) while requesting another (such as file B). At the same requesting another (such as file B). At the same time , another process holds the second resource time , another process holds the second resource (file B) while requesting the first one (file A) (file B) while requesting the first one (file A)
So neither process will ever have all its desired So neither process will ever have all its desired resources allocated to it and both will remain in resources allocated to it and both will remain in this DEAD LOCK state this DEAD LOCK state
Shared boolean lock1 =FALSE; /* shared variables*/Shared boolean lock1 =FALSE; /* shared variables*/
Shared boolean lock2 = FALSE;Shared boolean lock2 = FALSE;
Shared list L;Shared list L;
program for p1 program for p2program for p1 program for p2
…………… ……………. ………….. ………….
/* enter crit section to /* enter crit section to/* enter crit section to /* enter crit section to
delete elt from list */ * update length */delete elt from list */ * update length */
enter (lock1); enter (lock1);enter (lock1); enter (lock1);
<delete element>; <update length>;<delete element>; <update length>;
/* exit crtical section */ /* exit critical section *//* exit crtical section */ /* exit critical section */
exit (lock); exit (lock);exit (lock); exit (lock);
< intermediate computation>; <intermediate computation>;< intermediate computation>; <intermediate computation>;
/* enter crit section to /* enter crit section to/* enter crit section to /* enter crit section to
* update length */ * add elt to list */* update length */ * add elt to list */
enter (lock2); enter (lock1);enter (lock2); enter (lock1);
<update length>; <add element>;<update length>; <add element>;
/* exit critical section */ /* exit critical section *//* exit critical section */ /* exit critical section */
exit (lock2); exit (lock1);exit (lock2); exit (lock1);
……… ………. ……………. ……………
Multiple shared variables with disabled Multiple shared variables with disabled interruptsinterrupts
Ensuring consistency in related valuesEnsuring consistency in related values
Shared boolean lock1= FALSE; /* shared variables*/Shared boolean lock1= FALSE; /* shared variables*/
Shared boolean lock2=FALSE;Shared boolean lock2=FALSE;
Program for p1 praogran for p2Program for p1 praogran for p2
………… ……………………… ……………..
/* enter crit section to /* enter crit section to/* enter crit section to /* enter crit section to
* delete elt from list */ * update length */* delete elt from list */ * update length */
enter (lock1); enter (lock2);enter (lock1); enter (lock2);
<delete element>; <update length>;<delete element>; <update length>;
<intermediate computation>; <intermediate computation><intermediate computation>; <intermediate computation>
/* enter crit section to /* enter crit section to/* enter crit section to /* enter crit section to
* update length */ * add elt to list */* update length */ * add elt to list */
enter (lock2); enter (lock1);enter (lock2); enter (lock1);
<update length>; <add length>;<update length>; <add length>;
/* exit both crit sections */ /* exit both crit sections *//* exit both crit sections */ /* exit both crit sections */
exit (lock1); exit (lock2);exit (lock1); exit (lock2);
exit (lock2); exit (lock1);exit (lock2); exit (lock1);
…… …….. ………….... …………..