Movatterモバイル変換


[0]ホーム

URL:


PPTX, PDF66,821 views

Process synchronization in Operating Systems

The document discusses process synchronization in operating systems, emphasizing the need for coordination among processes accessing shared resources to avoid issues like data inconsistency. It covers several solutions including semaphores, monitors, and atomic transactions while also addressing classical synchronization problems such as the producer-consumer and readers-writers problems. Additionally, it highlights the importance of managing critical sections and introduces challenges like deadlock and starvation that can arise during synchronization.

Embed presentation

Downloaded 1,906 times
PROCESSSYNCHRONIZATIONINOPERATING SYSTEMS1ByRITU RANJAN SHRIVASTWAEmail: ranjanbhai.latest@gmail.com
TABLE OF CONTENTS• What is Process Synchronization and why it is needed• The Critical Section Problem• Peterson’s Solution• Synchronization Hardware• Semaphores• Applications of Semaphores• Classical Problems of Synchronizations• Synchronization Examples• Monitors• Atomic Transactions• References2
WHAT IS PROCESSSYNCHRONIZATION?• Several Processes run in an Operating System• Some of them share resources due to which problems likedata inconsistency may arise• For Example: One process changing the data in amemory location where another process is trying to readthe data from the same memory location. It is possiblethat the data read by the second process will beerroneous3
WHAT IS PROCESSSYNCHRONIZATION?• PRODUCER CONSUMER PROBLEM(or Bounded-Buffer Problem)• Problem: To ensure that the Producer should not addDATA when the Buffer is full and the Consumer shouldnot take data when the Buffer is empty4BufferProducer(process A)Consumer(process B)
WHAT IS PROCESSSYNCHRONIZATION?• SOLUTION PRODUCER CONSUMER PROBLEM• Using Semaphores (In computer science, particularly in operating systems,a semaphore is a variable or abstract data type that is used for controlling access, bymultiple processes, to a common resource in a concurrent system such asa multiprogramming operating system.)• Using Monitors (In concurrent programming, a monitor is a synchronizationconstruct that allows threads to have both mutual exclusion and the ability to wait(block) for a certain condition to become true)• Atomic Transactions (Atomic read-modify-write access to shared variables isavoided, as each of the two Count variables is updated only by a single thread. Also,these variables stay incremented all the time; the relation remains correct when theirvalues wrap around on an integer overflow)5
RACE CONDITION6What if T5 happened before T4??
CRITICAL SECTION PROBLEM• A section of code, common to n cooperatingprocesses, in which the processes may beaccessing common variables.• A Critical Section Environment contains:• Entry Section Code requesting entry into the critical section.• Critical Section Code in which only one process can execute atany one time.• Exit Section The end of the critical section, releasing or allowingothers in.• Remainder Section Rest of the code AFTER the critical section.7
CRITICAL SECTION PROBLEM• The critical section must ENFORCE ALL THREEof the following rules:• Mutual Exclusion: No more than one process canexecute in its critical section at one time.• Progress: If no one is in the critical section andsomeone wants in, then those processes not in theirremainder section must be able to decide in a finitetime who should go in.• Bounded Wait: All requesters must eventually be letinto the critical section8
CRITICAL SECTION PROBLEM9ENTRY SECTIONCRITICAL SECTIONEXIT SECTIONREMAINDER SECTION
PETERSON’S SOLUTION• To handle the problem of Critical Section (CS), Peterson gavean algorithm with a bounded waiting• Suppose there are N processes (P1, P2, … PN) and each ofthem at some point need to enter the Critical Section• A FLAG[] array of size N is maintained which is by default falseand whenever a process need to enter the critical section it hasto set its flag as true, i.e. suppose Pi wants to enter so it will setFLAG[i]=TRUE• There is another variable called TURN which indicates theprocess number which is currently to enter into the CS. Theprocess that enters into the CS while exiting would change theTURN to another number from among the list of readyprocesses10
PETERSON’S SOLUTION11• If turn is 2 (say) then P2 enters the CS and while exitingsets the turn as 3 and thus P3 breaks out of wait loopFLAG[i] = false
Synchronization Hardware• Problems of Critical Section are also solvable by hardware• Uniprocessor systems disables interrupts while a Process Pi isusing the CS but it is a great disadvantage in multiprocessorsystems• Some systems provide a lock functionality where a Processacquires a lock while entering the CS and releases the lockafter leaving it. Thus another process trying to enter CS cannotenter as the entry is locked. It can only do so if it is free byacquiring the lock itself• Another advanced approach is the Atomic Instructions (Non-Interruptible instructions).12
MUTEX LOCKS• As the synchronization hardware solution is not easy toimplement fro everyone, a strict software approach calledMutex Locks was introduced. In this approach, in theentry section of code, a LOCK is acquired over the criticalresources modified and used inside critical section, and inthe exit section that LOCK is released.• As the resource is locked while a process executes itscritical section hence no other process can access it13
SEMAPHORES• A more robust alternative to simple mutual exclusions is touse semaphores, which are integer variables for whichonly two ( atomic ) operations are defined, the wait andsignal operations, as shown in the following figure• As given here, these are not atomic as written in "macrocode". We define these operations, however, to be atomic(Protected by a hardware lock.)14WAIT ( S ):while ( S <= 0 );S = S - 1;SIGNAL ( S ):S = S + 1;
SEMAPHORES• FORMAT:wait ( mutex ); // Mutual exclusion: mutex init to 1.CRITICAL SECTIONsignal( mutex );REMAINDER• Note that not only must the variable-changing steps ( S-- andS++ ) be indivisible, it is also necessary that for the waitoperation when the test proves false that there be nointerruptions before S gets decremented. It IS okay, however,for the busy loop to be interrupted when the test is true, whichprevents the system from hanging forever15
SEMAPHORES• PROPERTIES1. Simple2. Works with many processes3. Can have many different critical sections with differentsemaphores4. Each critical section has unique access semaphores5. Can permit multiple processes into the critical section atonce, if desirable.16
SEMAPHORES• TYPESSemaphores are mainly of two types:1. Binary SemaphoreIt is a special form of semaphore used for implementing mutualexclusion, hence it is often called Mutex. A binary semaphore isinitialized to 1 and only takes the value 0 and 1 during execution ofa program.2. Counting SemaphoresThese are used to implement bounded concurrency.17
SEMAPHORES• Semaphores can be used to force synchronization (precedence ) if the preceding process does a signal at theend, and the follower does wait at beginning. For example,here we want P1 to execute before P2.P1: P2:statement 1; wait ( synch );signal ( synch ); statement 2;• To PREVENT looping, we redefine the semaphore structure as:typedef struct {int value;struct process *list; //linked list of PTBL waiting on S} SEMAPHORE;18
SEMAPHORES• It's critical that these be atomic - in uniprocessors we candisable interrupts, but in multiprocessors othermechanisms for atomicity are needed.19SEMAPHORE s;wait(s) {s.value = s.value - 1;if ( s.value < 0 ) {add this process to s.L;block;}}SEMAPHORE s;signal(s) {s.value = s.value + 1;if ( s.value <= 0 ) {remove a process P from s.L;wakeup(P);}}
SEMAPHORES• DEADLOCK• One important problem that can arise when using semaphores to blockprocesses waiting for a limited resource is the problem of deadlocks, whichoccur when multiple processes are blocked, each waiting for a resource thatcan only be freed by one of the other ( blocked ) processes, as illustrated inthe following example.20
SEMAPHORES• STARVATION• Another problem to consider is that of starvation, inwhich one or more processes gets blocked forever, andnever get a chance to take their turn in the critical section.For example, in the semaphores above, we did notspecify the algorithms for adding processes to the waitingqueue in the semaphore in the wait( ) call, or selectingone to be removed from the queue in the signal( ) call. Ifthe method chosen is a FIFO queue, then every processwill eventually get their turn, but if a LIFO queue isimplemented instead, then the first process to startwaiting could starve.21
THE BOUNDED-BUFFER PROBLEM• This is a generalization of the producer-consumerproblem wherein access is controlled to a shared group ofbuffers of a limited size.• In this solution, the two counting semaphores "full" and"empty" keep track of the current number of full and emptybuffers respectively ( and initialized to 0 and Nrespectively. ) The binary semaphore mutex controlsaccess to the critical section. The producer and consumerprocesses are nearly identical - One can think of theproducer as producing full buffers, and the consumerproducing empty buffers.22
THE BOUNDED-BUFFER PROBLEM23PRODUCERCONSUMER
THE READERS-WRITERS PROBLEM• THE READERS/WRITERS PROBLEM:• This is the same as the Producer / Consumer problem except - we nowcan have many concurrent readers and one exclusive writer.• Locks: are shared (for the readers) and exclusive (for the writer).• Two possible ( contradictory ) guidelines can be used:• No reader is kept waiting unless a writer holds the lock (the readers haveprecedence).• If a writer is waiting for access, no new reader gains access (writer hasprecedence).• ( NOTE: starvation can occur on either of these rules if they are followedrigorously.)24
THE READERS-WRITERS PROBLEM25Reader:do {wait( mutex ); /* Allow 1 reader in entry*/readcount = readcount + 1;if readcount == 1 then wait(wrt ); /* 1st reader locks writer */signal( mutex );/* reading is performed */wait( mutex );readcount = readcount - 1;if readcount == 0 then signal(wrt ); /*last reader frees writer */signal( mutex );} while(TRUE);Writer:do {wait( wrt );/* writing is performed */signal( wrt );} while(TRUE);THE READERS/WRITERS PROBLEM:BINARY_SEMAPHORE wrt = 1;BINARY_SEMAPHORE mutex = 1;int readcount = 0;
DINING PHILOSOPHERS PROBLEM26• Five philosophers sitting at a round diningtable to eat• Each one has got a plate and one chopstick atthe right side of each plate• To start eating each of them need a plate andtwo chopsticks• Thus, clearly there will be a deadlock andstarvation because of the limited number ofchopsticks• This can be solved by either:• Allow only 4 philosophers to be hungry ata time• Allow pickup only if both chopsticks areavailable. ( Done in critical section )• Odd # philosopher always picks up leftchopstick 1st, even # philosopher alwayspicks up right chopstick 1st
DINING PHILOSOPHERS PROBLEM• One possible solution, as shown in the following code section, is touse a set of five semaphores ( chopsticks[ 5 ] ), and to have eachhungry philosopher first wait on their left chopstick ( chopsticks[ i ] ),and then wait on their right chopstick ( chopsticks[ ( i + 1 ) % 5 ] )27
SYNCHRONIZATION EXAMPLES• SYNCHRONIZATION IN WINDOWS• SYNCHRONIZATION IN LINUX28
MONITORS• High-level synchronization construct that allows the safesharing of an abstract data type among concurrentprocesses.• Semaphores can be very useful for solving concurrencyproblems, but only if programmers use themproperly. If even one process fails to abide by the properuse of semaphores, either accidentally or deliberately,then the whole system breaks down.29
MONITORS• A monitor is essentially aclass, in which all data isprivate, and with the specialrestriction that only onemethod within any givenmonitor object may beactive at the same time.• An additional restriction isthat monitor methods mayonly access the shared datawithin the monitor and anydata passed to them asparameters, i.e. they cannotaccess any data external tothe monitor.30
MONITORS• In order to fully realize the potential of monitors, weneed to introduce one additional new data type,known as a condition.• A variable of type condition has only two legaloperations, wait and signal. I.e. if X was definedas type condition, then legal operations would beX.wait( ) and X.signal( )• The wait operation blocks a process until someother process calls signal, and adds the blockedprocess onto a list associated with that condition.• The signal process does nothing if there are noprocesses waiting on that condition. Otherwise itwakes up exactly one process from thecondition's list of waiting processes. ( Contrastthis with counting semaphores, which alwaysaffect the semaphore on a signal call. )31
ATOMIC TRANSACTIONS• Database operations frequently need to carry out atomictransactions, in which the entire transaction must eithercomplete or not occur at all.• The classic example is a transfer of funds, which involveswithdrawing funds from one account and depositing them intoanother - Either both halves of the transaction must complete,or neither must complete.• Operating Systems can be viewed as having many of the sameneeds and problems as databases, in that an OS can be saidto manage a small database of process-related information. Assuch, OSs can benefit from emulating some of the techniquesoriginally developed for databases.32
ATOMIC TRANSACTIONS• FUNDAMENTAL PRINCIPLES – A C I D• Atomicity – to outside world, transaction happensindivisibly• Consistency – transaction preserves system invariants• Isolated – transactions do not interfere with each other• Durable – once a transaction “commits,” the changes arepermanent33
REFERENCES• https://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/5_Synchronization.html• http://www.studytonight.com/operating-system/process-synchronization34

Recommended

PDF
Process Scheduling in OS
PPTX
Process synchronization
PPTX
Inter Process Communication
PPT
Deadlock
PDF
Semaphores
PPT
Chapter 6 - Process Synchronization
PPT
Interprocess communication (IPC) IN O.S
PPTX
Concurrency Control in Database Management System
PPT
Disk scheduling
PDF
OS - Process Concepts
PPT
deadlock avoidance
PPTX
Deadlock dbms
PPTX
Process scheduling
PPTX
Semaphore
PPTX
Critical section problem in operating system.
PDF
Process scheduling (CPU Scheduling)
PPTX
INTER PROCESS COMMUNICATION (IPC).pptx
 
PPTX
DeadLock in Operating-Systems
PPTX
SCHEDULING ALGORITHMS
PPTX
Memory Management in OS
PPTX
Deadlock ppt
PPTX
Demand paging
PPTX
CPU Scheduling in OS Presentation
PPTX
Deadlocks in operating system
PPTX
Deadlock Prevention
PPTX
Directory structure
PPTX
Concurrency control
PPT
OS Process Synchronization, semaphore and Monitors
PPT
Types dbms

More Related Content

PDF
Process Scheduling in OS
PPTX
Process synchronization
PPTX
Inter Process Communication
PPT
Deadlock
PDF
Semaphores
PPT
Chapter 6 - Process Synchronization
PPT
Interprocess communication (IPC) IN O.S
Process Scheduling in OS
Process synchronization
Inter Process Communication
Deadlock
Semaphores
Chapter 6 - Process Synchronization
Interprocess communication (IPC) IN O.S

What's hot

PPTX
Concurrency Control in Database Management System
PPT
Disk scheduling
PDF
OS - Process Concepts
PPT
deadlock avoidance
PPTX
Deadlock dbms
PPTX
Process scheduling
PPTX
Semaphore
PPTX
Critical section problem in operating system.
PDF
Process scheduling (CPU Scheduling)
PPTX
INTER PROCESS COMMUNICATION (IPC).pptx
 
PPTX
DeadLock in Operating-Systems
PPTX
SCHEDULING ALGORITHMS
PPTX
Memory Management in OS
PPTX
Deadlock ppt
PPTX
Demand paging
PPTX
CPU Scheduling in OS Presentation
PPTX
Deadlocks in operating system
PPTX
Deadlock Prevention
PPTX
Directory structure
PPTX
Concurrency control
Concurrency Control in Database Management System
Disk scheduling
OS - Process Concepts
deadlock avoidance
Deadlock dbms
Process scheduling
Semaphore
Critical section problem in operating system.
Process scheduling (CPU Scheduling)
INTER PROCESS COMMUNICATION (IPC).pptx
 
DeadLock in Operating-Systems
SCHEDULING ALGORITHMS
Memory Management in OS
Deadlock ppt
Demand paging
CPU Scheduling in OS Presentation
Deadlocks in operating system
Deadlock Prevention
Directory structure
Concurrency control

Viewers also liked

PPT
OS Process Synchronization, semaphore and Monitors
PPT
Types dbms
PDF
Operating Systems - Synchronization
PPT
Process synchronization(deepa)
DOCX
Operating System Process Synchronization
PDF
Web technology
PDF
Unit II - 3 - Operating System - Process Synchronization
PPT
Web Tech
 
PPTX
Operating system critical section
PPTX
Process synchronization in operating system
PPT
Process Synchronization And Deadlocks
OS Process Synchronization, semaphore and Monitors
Types dbms
Operating Systems - Synchronization
Process synchronization(deepa)
Operating System Process Synchronization
Web technology
Unit II - 3 - Operating System - Process Synchronization
Web Tech
 
Operating system critical section
Process synchronization in operating system
Process Synchronization And Deadlocks

Similar to Process synchronization in Operating Systems

PDF
OPERATING SYSTEM NOTESS ppt Unit 2.1.pdf
PDF
Ch5 process synchronization
PDF
CH05.pdf
PDF
OS Process synchronization Unit3 synchronization
PPT
Operating system Process Syncronization.ppt
PPT
Ipc feb4
PPT
PPTX
Process Synchronization in Operating Systems
DOCX
Critical section operating system
PPT
Section06-Syncopkojiojoijnnjkhuubgfffppt
PPTX
MODULE 3 process synchronizationnnn.pptx
PPT
Operating Systems - "Chapter 5 Process Synchronization"
PPTX
Operating system 24 mutex locks and semaphores
PPTX
Process Synchronization in operating system | mutex | semaphore | race condition
PPT
Process Synchronization -1.ppt
PPT
Lecture18-19 (1).ppt
PPTX
Lecture 9 - Process Synchronization.pptx
PPTX
Interprocess Communication important topic in iOS .pptx
PPT
Inter process communication
PPTX
process synchronization in Operating system ppt.pptx
OPERATING SYSTEM NOTESS ppt Unit 2.1.pdf
Ch5 process synchronization
CH05.pdf
OS Process synchronization Unit3 synchronization
Operating system Process Syncronization.ppt
Ipc feb4
Process Synchronization in Operating Systems
Critical section operating system
Section06-Syncopkojiojoijnnjkhuubgfffppt
MODULE 3 process synchronizationnnn.pptx
Operating Systems - "Chapter 5 Process Synchronization"
Operating system 24 mutex locks and semaphores
Process Synchronization in operating system | mutex | semaphore | race condition
Process Synchronization -1.ppt
Lecture18-19 (1).ppt
Lecture 9 - Process Synchronization.pptx
Interprocess Communication important topic in iOS .pptx
Inter process communication
process synchronization in Operating system ppt.pptx

Recently uploaded

PDF
CXC-AD Associate Degree Handbook (Revised)
PDF
ASRB NET 2025 Paper GENETICS AND PLANT BREEDING ARS, SMS & STODiscussion | Co...
PPTX
Elderly in India: The Changing Scenario.pptx
 
PDF
Unit 2: Functions of Management (POSDC.)
PPTX
Organize order into course in Odoo 18.2 _ Odoo 19
PDF
Unit 4_ small scale industries & Entrepreneurship
PDF
Risk Management and Regulatory Compliance - by Ms. Oceana Wong
PDF
Unit 1- Basics of Management Cha. of Magmt
PPTX
Introduction to Beauty Care and Wellness Services.pptx-day fcs 3rd quarter tl...
PDF
Photoperiod Classification of Vegetable Plants.pdf
PPTX
Photography Pillar 1 The Subject PowerPoint
PDF
UGC NET Paper 1 Syllabus | 10 Units Complete Guide for NTA JRF
PPTX
Prelims - History and Geography Quiz - Around the World in 80 Questions - IITK
PPTX
Time Series Analysis - Method of Simple Moving Average 3 Year and 4 Year Movi...
PDF
Deep Research and Analysis - by Ms. Oceana Wong
PPTX
Masterclass on Cybercrime, Scams & Safety Hacks.pptx
PDF
Conferencia de Abertura_Virgilio Almeida.pdf
PPTX
LYMPHATIC SYSTEM.pptx it includes lymph, lymph nodes, bone marrow, spleen
PPTX
Plant Breeding: Its History and Contribution
PDF
Cattolica University - Lab Generative and Agentic AI - Mario Bencivinni
CXC-AD Associate Degree Handbook (Revised)
ASRB NET 2025 Paper GENETICS AND PLANT BREEDING ARS, SMS & STODiscussion | Co...
Elderly in India: The Changing Scenario.pptx
 
Unit 2: Functions of Management (POSDC.)
Organize order into course in Odoo 18.2 _ Odoo 19
Unit 4_ small scale industries & Entrepreneurship
Risk Management and Regulatory Compliance - by Ms. Oceana Wong
Unit 1- Basics of Management Cha. of Magmt
Introduction to Beauty Care and Wellness Services.pptx-day fcs 3rd quarter tl...
Photoperiod Classification of Vegetable Plants.pdf
Photography Pillar 1 The Subject PowerPoint
UGC NET Paper 1 Syllabus | 10 Units Complete Guide for NTA JRF
Prelims - History and Geography Quiz - Around the World in 80 Questions - IITK
Time Series Analysis - Method of Simple Moving Average 3 Year and 4 Year Movi...
Deep Research and Analysis - by Ms. Oceana Wong
Masterclass on Cybercrime, Scams & Safety Hacks.pptx
Conferencia de Abertura_Virgilio Almeida.pdf
LYMPHATIC SYSTEM.pptx it includes lymph, lymph nodes, bone marrow, spleen
Plant Breeding: Its History and Contribution
Cattolica University - Lab Generative and Agentic AI - Mario Bencivinni

Process synchronization in Operating Systems

  • 1.
    PROCESSSYNCHRONIZATIONINOPERATING SYSTEMS1ByRITU RANJANSHRIVASTWAEmail: ranjanbhai.latest@gmail.com
  • 2.
    TABLE OF CONTENTS•What is Process Synchronization and why it is needed• The Critical Section Problem• Peterson’s Solution• Synchronization Hardware• Semaphores• Applications of Semaphores• Classical Problems of Synchronizations• Synchronization Examples• Monitors• Atomic Transactions• References2
  • 3.
    WHAT IS PROCESSSYNCHRONIZATION?•Several Processes run in an Operating System• Some of them share resources due to which problems likedata inconsistency may arise• For Example: One process changing the data in amemory location where another process is trying to readthe data from the same memory location. It is possiblethat the data read by the second process will beerroneous3
  • 4.
    WHAT IS PROCESSSYNCHRONIZATION?•PRODUCER CONSUMER PROBLEM(or Bounded-Buffer Problem)• Problem: To ensure that the Producer should not addDATA when the Buffer is full and the Consumer shouldnot take data when the Buffer is empty4BufferProducer(process A)Consumer(process B)
  • 5.
    WHAT IS PROCESSSYNCHRONIZATION?•SOLUTION PRODUCER CONSUMER PROBLEM• Using Semaphores (In computer science, particularly in operating systems,a semaphore is a variable or abstract data type that is used for controlling access, bymultiple processes, to a common resource in a concurrent system such asa multiprogramming operating system.)• Using Monitors (In concurrent programming, a monitor is a synchronizationconstruct that allows threads to have both mutual exclusion and the ability to wait(block) for a certain condition to become true)• Atomic Transactions (Atomic read-modify-write access to shared variables isavoided, as each of the two Count variables is updated only by a single thread. Also,these variables stay incremented all the time; the relation remains correct when theirvalues wrap around on an integer overflow)5
  • 6.
    RACE CONDITION6What ifT5 happened before T4??
  • 7.
    CRITICAL SECTION PROBLEM•A section of code, common to n cooperatingprocesses, in which the processes may beaccessing common variables.• A Critical Section Environment contains:• Entry Section Code requesting entry into the critical section.• Critical Section Code in which only one process can execute atany one time.• Exit Section The end of the critical section, releasing or allowingothers in.• Remainder Section Rest of the code AFTER the critical section.7
  • 8.
    CRITICAL SECTION PROBLEM•The critical section must ENFORCE ALL THREEof the following rules:• Mutual Exclusion: No more than one process canexecute in its critical section at one time.• Progress: If no one is in the critical section andsomeone wants in, then those processes not in theirremainder section must be able to decide in a finitetime who should go in.• Bounded Wait: All requesters must eventually be letinto the critical section8
  • 9.
    CRITICAL SECTION PROBLEM9ENTRYSECTIONCRITICAL SECTIONEXIT SECTIONREMAINDER SECTION
  • 10.
    PETERSON’S SOLUTION• Tohandle the problem of Critical Section (CS), Peterson gavean algorithm with a bounded waiting• Suppose there are N processes (P1, P2, … PN) and each ofthem at some point need to enter the Critical Section• A FLAG[] array of size N is maintained which is by default falseand whenever a process need to enter the critical section it hasto set its flag as true, i.e. suppose Pi wants to enter so it will setFLAG[i]=TRUE• There is another variable called TURN which indicates theprocess number which is currently to enter into the CS. Theprocess that enters into the CS while exiting would change theTURN to another number from among the list of readyprocesses10
  • 11.
    PETERSON’S SOLUTION11• Ifturn is 2 (say) then P2 enters the CS and while exitingsets the turn as 3 and thus P3 breaks out of wait loopFLAG[i] = false
  • 12.
    Synchronization Hardware• Problemsof Critical Section are also solvable by hardware• Uniprocessor systems disables interrupts while a Process Pi isusing the CS but it is a great disadvantage in multiprocessorsystems• Some systems provide a lock functionality where a Processacquires a lock while entering the CS and releases the lockafter leaving it. Thus another process trying to enter CS cannotenter as the entry is locked. It can only do so if it is free byacquiring the lock itself• Another advanced approach is the Atomic Instructions (Non-Interruptible instructions).12
  • 13.
    MUTEX LOCKS• Asthe synchronization hardware solution is not easy toimplement fro everyone, a strict software approach calledMutex Locks was introduced. In this approach, in theentry section of code, a LOCK is acquired over the criticalresources modified and used inside critical section, and inthe exit section that LOCK is released.• As the resource is locked while a process executes itscritical section hence no other process can access it13
  • 14.
    SEMAPHORES• A morerobust alternative to simple mutual exclusions is touse semaphores, which are integer variables for whichonly two ( atomic ) operations are defined, the wait andsignal operations, as shown in the following figure• As given here, these are not atomic as written in "macrocode". We define these operations, however, to be atomic(Protected by a hardware lock.)14WAIT ( S ):while ( S <= 0 );S = S - 1;SIGNAL ( S ):S = S + 1;
  • 15.
    SEMAPHORES• FORMAT:wait (mutex ); // Mutual exclusion: mutex init to 1.CRITICAL SECTIONsignal( mutex );REMAINDER• Note that not only must the variable-changing steps ( S-- andS++ ) be indivisible, it is also necessary that for the waitoperation when the test proves false that there be nointerruptions before S gets decremented. It IS okay, however,for the busy loop to be interrupted when the test is true, whichprevents the system from hanging forever15
  • 16.
    SEMAPHORES• PROPERTIES1. Simple2.Works with many processes3. Can have many different critical sections with differentsemaphores4. Each critical section has unique access semaphores5. Can permit multiple processes into the critical section atonce, if desirable.16
  • 17.
    SEMAPHORES• TYPESSemaphores aremainly of two types:1. Binary SemaphoreIt is a special form of semaphore used for implementing mutualexclusion, hence it is often called Mutex. A binary semaphore isinitialized to 1 and only takes the value 0 and 1 during execution ofa program.2. Counting SemaphoresThese are used to implement bounded concurrency.17
  • 18.
    SEMAPHORES• Semaphores canbe used to force synchronization (precedence ) if the preceding process does a signal at theend, and the follower does wait at beginning. For example,here we want P1 to execute before P2.P1: P2:statement 1; wait ( synch );signal ( synch ); statement 2;• To PREVENT looping, we redefine the semaphore structure as:typedef struct {int value;struct process *list; //linked list of PTBL waiting on S} SEMAPHORE;18
  • 19.
    SEMAPHORES• It's criticalthat these be atomic - in uniprocessors we candisable interrupts, but in multiprocessors othermechanisms for atomicity are needed.19SEMAPHORE s;wait(s) {s.value = s.value - 1;if ( s.value < 0 ) {add this process to s.L;block;}}SEMAPHORE s;signal(s) {s.value = s.value + 1;if ( s.value <= 0 ) {remove a process P from s.L;wakeup(P);}}
  • 20.
    SEMAPHORES• DEADLOCK• Oneimportant problem that can arise when using semaphores to blockprocesses waiting for a limited resource is the problem of deadlocks, whichoccur when multiple processes are blocked, each waiting for a resource thatcan only be freed by one of the other ( blocked ) processes, as illustrated inthe following example.20
  • 21.
    SEMAPHORES• STARVATION• Anotherproblem to consider is that of starvation, inwhich one or more processes gets blocked forever, andnever get a chance to take their turn in the critical section.For example, in the semaphores above, we did notspecify the algorithms for adding processes to the waitingqueue in the semaphore in the wait( ) call, or selectingone to be removed from the queue in the signal( ) call. Ifthe method chosen is a FIFO queue, then every processwill eventually get their turn, but if a LIFO queue isimplemented instead, then the first process to startwaiting could starve.21
  • 22.
    THE BOUNDED-BUFFER PROBLEM•This is a generalization of the producer-consumerproblem wherein access is controlled to a shared group ofbuffers of a limited size.• In this solution, the two counting semaphores "full" and"empty" keep track of the current number of full and emptybuffers respectively ( and initialized to 0 and Nrespectively. ) The binary semaphore mutex controlsaccess to the critical section. The producer and consumerprocesses are nearly identical - One can think of theproducer as producing full buffers, and the consumerproducing empty buffers.22
  • 23.
  • 24.
    THE READERS-WRITERS PROBLEM•THE READERS/WRITERS PROBLEM:• This is the same as the Producer / Consumer problem except - we nowcan have many concurrent readers and one exclusive writer.• Locks: are shared (for the readers) and exclusive (for the writer).• Two possible ( contradictory ) guidelines can be used:• No reader is kept waiting unless a writer holds the lock (the readers haveprecedence).• If a writer is waiting for access, no new reader gains access (writer hasprecedence).• ( NOTE: starvation can occur on either of these rules if they are followedrigorously.)24
  • 25.
    THE READERS-WRITERS PROBLEM25Reader:do{wait( mutex ); /* Allow 1 reader in entry*/readcount = readcount + 1;if readcount == 1 then wait(wrt ); /* 1st reader locks writer */signal( mutex );/* reading is performed */wait( mutex );readcount = readcount - 1;if readcount == 0 then signal(wrt ); /*last reader frees writer */signal( mutex );} while(TRUE);Writer:do {wait( wrt );/* writing is performed */signal( wrt );} while(TRUE);THE READERS/WRITERS PROBLEM:BINARY_SEMAPHORE wrt = 1;BINARY_SEMAPHORE mutex = 1;int readcount = 0;
  • 26.
    DINING PHILOSOPHERS PROBLEM26•Five philosophers sitting at a round diningtable to eat• Each one has got a plate and one chopstick atthe right side of each plate• To start eating each of them need a plate andtwo chopsticks• Thus, clearly there will be a deadlock andstarvation because of the limited number ofchopsticks• This can be solved by either:• Allow only 4 philosophers to be hungry ata time• Allow pickup only if both chopsticks areavailable. ( Done in critical section )• Odd # philosopher always picks up leftchopstick 1st, even # philosopher alwayspicks up right chopstick 1st
  • 27.
    DINING PHILOSOPHERS PROBLEM•One possible solution, as shown in the following code section, is touse a set of five semaphores ( chopsticks[ 5 ] ), and to have eachhungry philosopher first wait on their left chopstick ( chopsticks[ i ] ),and then wait on their right chopstick ( chopsticks[ ( i + 1 ) % 5 ] )27
  • 28.
    SYNCHRONIZATION EXAMPLES• SYNCHRONIZATIONIN WINDOWS• SYNCHRONIZATION IN LINUX28
  • 29.
    MONITORS• High-level synchronizationconstruct that allows the safesharing of an abstract data type among concurrentprocesses.• Semaphores can be very useful for solving concurrencyproblems, but only if programmers use themproperly. If even one process fails to abide by the properuse of semaphores, either accidentally or deliberately,then the whole system breaks down.29
  • 30.
    MONITORS• A monitoris essentially aclass, in which all data isprivate, and with the specialrestriction that only onemethod within any givenmonitor object may beactive at the same time.• An additional restriction isthat monitor methods mayonly access the shared datawithin the monitor and anydata passed to them asparameters, i.e. they cannotaccess any data external tothe monitor.30
  • 31.
    MONITORS• In orderto fully realize the potential of monitors, weneed to introduce one additional new data type,known as a condition.• A variable of type condition has only two legaloperations, wait and signal. I.e. if X was definedas type condition, then legal operations would beX.wait( ) and X.signal( )• The wait operation blocks a process until someother process calls signal, and adds the blockedprocess onto a list associated with that condition.• The signal process does nothing if there are noprocesses waiting on that condition. Otherwise itwakes up exactly one process from thecondition's list of waiting processes. ( Contrastthis with counting semaphores, which alwaysaffect the semaphore on a signal call. )31
  • 32.
    ATOMIC TRANSACTIONS• Databaseoperations frequently need to carry out atomictransactions, in which the entire transaction must eithercomplete or not occur at all.• The classic example is a transfer of funds, which involveswithdrawing funds from one account and depositing them intoanother - Either both halves of the transaction must complete,or neither must complete.• Operating Systems can be viewed as having many of the sameneeds and problems as databases, in that an OS can be saidto manage a small database of process-related information. Assuch, OSs can benefit from emulating some of the techniquesoriginally developed for databases.32
  • 33.
    ATOMIC TRANSACTIONS• FUNDAMENTALPRINCIPLES – A C I D• Atomicity – to outside world, transaction happensindivisibly• Consistency – transaction preserves system invariants• Isolated – transactions do not interfere with each other• Durable – once a transaction “commits,” the changes arepermanent33
  • 34.

[8]ページ先頭

©2009-2025 Movatter.jp