+ All Categories
Home > Documents > 6 Synchronisation

6 Synchronisation

Date post: 05-Dec-2014
Category:
Upload: loganathan-ramasamy
View: 1,209 times
Download: 1 times
Share this document with a friend
Description:
Synchronisation
26
Process Synchronization Background The Critical-Section Problem Peterson’s Solution Peterson’s Solution Synchronization Hardware Semaphores Classic Problems of Synchronization Monitors
Transcript
Page 1: 6 Synchronisation

Process Synchronization

BackgroundThe Critical-Section ProblemPeterson’s SolutionPeterson’s SolutionSynchronization HardwareSemaphoresClassic Problems of SynchronizationMonitors

Page 2: 6 Synchronisation

• Concurrent access to shared data may result in data inconsistency• Maintaining data consistency requires mechanisms to ensure the

orderly execution of cooperating processes• A solution to the consumer-producer problem that fills all the

buffers can have an integer count that keeps track of the numberof full buffers. Initially, count is set to 0. It is incremented by theproducer after it produces a new buffer and is decremented bythe consumer after it consumes a buffer.

1. Background

the consumer after it consumes a buffer.

2Loganatahn R, CSE, HKBKCE

while (true) {while (count == BUFFER_SIZE)

; // do nothingbuffer [in] = nextProduced;in = (in + 1) % BUFFER_SIZE;count++;

}

while (true) {while (count == 0); // do nothingnextConsumed = buffer[out];out = (out + 1) % BUFFER_SIZE;count--;nextConsumed}

Producer Consumer

Page 3: 6 Synchronisation

• Where several processes access and manipulate the same data concurrentlyand the outcome of the execution depends on the particular order in whichthe access takes place, is called a race condition

• To guard against the race condition, ensure that only one process at a time canbe manipulating the data which require that the processes be synchronized

1. Background Contd…

• count++ could be implemented asregister1 = countregister1 = register1 + 1count = register1

• count-- could be implemented asregister2 = countregister2 = register2 - 1count = register2

3Loganatahn R, CSE, HKBKCE

count = register1

• The concurrent execution of "counter++" and "counter--" is equivalent to asequential execution where the lower-level statements are interleaved insome arbitrary order but the order within each high-level statement ispreserved

• Consider this execution interleaving with “count = 5” initially:S0: producer execute register1 = count {register1 = 5}S1: producer execute register1 = register1 + 1 {register1 = 6}S2: consumer execute register2 = count {register2 = 5}S3: consumer execute register2 = register2 - 1 {register2 = 4}S4: producer execute count = register1 {count = 6 }S5: consumer execute count = register2 {count = 4}

Page 4: 6 Synchronisation

• Each process in a system has a segment of code, called a criticalsection, in which the process may be changing commonvariables, updating a table, writing a file, and so on

• When one process is executing in its critical section, no otherprocess is to be allowed to execute in its critical section is knownas critical-section problem

• Each process must request permission to enter its critical sectionand the code implementing this request is the entry section

• The critical section is followed by an exit section and the

2. The Critical-Section Problem

• The critical section is followed by an exit section and theremaining code is the remainder section

• General structure of a typical process

4Loganatahn R, CSE, HKBKCE

do{

critical section

remainder section} while (TRUE);

entry section

exit section

Page 5: 6 Synchronisation

• A solution to the critical-section problem must satisfy the following threerequirements

1. Mutual Exclusion - If process Pi is executing in its critical section, then noother processes can be executing in their critical sections

2. Progress - If no process is executing in its critical section and there exist someprocesses that wish to enter their critical section, then only those processesthat are not executing in their remainder sections can participate in thedecision on which will enter its critical section next, and this selection cannotbe postponed indefinitely

2. The Critical-Section Problem Contd…

be postponed indefinitely3. Bounded Waiting - There exists a bound, or limit, on the number of times

that other processes are allowed to enter their critical sections after aprocess has made a request to enter its critical section and before thatrequest is granted Assume that each process executes at a nonzero speed No assumption concerning relative speed of the N processes

• Two approaches are used to handle critical sections in OS (1) preemptivekernels and (2) nonpreemptive kernels

5Loganatahn R, CSE, HKBKCE

Page 6: 6 Synchronisation

• Restricted to Two Process only• Two data items shared is between the process P1 & P2 (Pi & Pj)

– int turn;– Boolean flag[2]

• The variable turn indicates whose turn it is to enter the criticalsection. If turn == i, then process Pi is allowed

• The flag array is used to indicate if a process is ready to enter thecritical section. flag[i] = true implies that process Pi is ready

• Algorithm for P

3. Peterson's Solution

• Algorithm for Pi

6Loganatahn R, CSE, HKBKCE

do {flag[ i ] = TRUE;turn = j ;while (flag[j] && turn == j ) ;

critical sectionflag[i] = FALSE;

remainder section} while (TRUE);

Page 7: 6 Synchronisation

• To Prove1.Mutual exclusion is preserved.

– Pi enters its critical section only if either flag[j] == false orturn = I

– if both processes are executing in their critical sections at thesame time, then flag [i] == flag [j] == true(NOT Possible)

2.The progress requirement is satisfied.– Since Pi does not change the value of the variable turn while

3. Peterson's Solution Contd…

– Since Pi does not change the value of the variable turn whileexecuting the while statement, Pi- will enter the criticalsection

3.The bounded-waiting requirement is met.– Once Pj exits its critical section, it will reset flag[j] to false,

allowing Pi to enter its critical section.

7Loganatahn R, CSE, HKBKCE

Page 8: 6 Synchronisation

• Race conditions are prevented by requiring that criticalregions be protected by locks i.e., a process must acquirea lock before entering a critical section and it releases thelock when it exits the critical section.

4. Synchronization Hardware

do {

critical section

remainder section} while (TRUE);

release lock

acquire lock

• All these solutions are based on the locking, however, thedesign of such locks can be quite sophisticated

• Uniprocessors – If interrupts could be disabled duringcritical section

• Modern machines provide special atomic(non-interruptable) hardware instructions– Either test memory word and set value - TestAndSet()– Or swap contents of two memory words – Swap()

8Loganatahn R, CSE, HKBKCE

} while (TRUE);

Page 9: 6 Synchronisation

TestAndndSet Instruction

• if two TestAndSet () instructions are executed simultaneously(each on a different CPU), they will be executed sequentially in

4. Synchronization Hardware Contd…

boolean TestAndSet (boolean *target){

boolean rv = *target;*target = TRUE;return rv:

}

(each on a different CPU), they will be executed sequentially insome arbitrary order

Mutual-exclusion implementation with TestAndSet ( )

9Loganatahn R, CSE, HKBKCE

while (true) {while ( TestAndSet (&lock ));

// critical sectionlock = FALSE;

// remainder section}

Page 10: 6 Synchronisation

Swap() instruction

Mutual-exclusion implementation with the Swap()• A global Boolean variable lock is declared and is initialized to false and each

4. Synchronization Hardware Contd…

void Swap (boolean *a, boolean *b){

boolean temp = *a;*a = *b;*b = temp:

}

• A global Boolean variable lock is declared and is initialized to false and eachprocess has a local Boolean variable key

10Loganatahn R, CSE, HKBKCE

while (true) {

key = TRUE;

while ( key == TRUE)

Swap (&lock, &key );

// critical section

lock = FALSE;

// remainder section

}

The above both algorithms donot satisfy the bounded-waitingrequirement

Page 11: 6 Synchronisation

Bounded-waiting mutual exclusion with TestAndSet ().

4. Synchronization Hardware Contd…

do {waiting[i] = TRUE;key = TRUE;while (waiting[i] && key)

key = TestAndSet(&lock);waiting[i] = FALSE;// critical sectionj = (i + 1) % n;while ((j != i) && !waiting[j])

Common data structures are initialized to falseboolean waiting[n]; & boolean lock;

To prove the mutual exclusionProcess Pi can enter its CS only if either waiting[i] = false or

key = false. The first process to execute the TestAndSet ()will find key = false and all others must wait. The variablewaiting[i] can become false only if another process leavesits critical section i.e. only one waiting [i] is set to false,maintaining the mutual-exclusion requirement

To prove that the progress(Same as above)

11Loganatahn R, CSE, HKBKCE

while ((j != i) && !waiting[j])j = (j + 1) % n;

if (j == i)lock = FALSE;

elsewaiting[j] = FALSE;

// remainder section} while (TRUE);

To prove that the progress(Same as above)Process exiting the CS either sets lock to false or sets

waiting[j] to false allow a process that is waiting to enterits critical section to proceed

To prove that the bounded-waitingProcess which leaves its CS, scans the array waiting in the

cyclic ordering (i+1, i+2,...,n-1, 0,..., i)It designates thefirst process in this ordering that is in the entry section(waiting [j] =- true) as the next one to enter the criticalsection. Any process waiting to enter its critical sectionwill do so within n-1 turns

Page 12: 6 Synchronisation

• Synchronization tool that does not require busy waiting• Semaphore S is integer variable, apart from initialization, is accessed only by 2

standard atomic operations: wait () and signal () Originally called P() and V()• The Definition of

• When one process modifies the semaphore, no other process can modify it

• 5.1 Usage

5. Semaphores

wait (S) {while (S <= 0); // no-opS--;

}

signal (S) {S++;

}

• 5.1 Usage• Counting semaphore – integer value can range over an unrestricted domain• Binary semaphore – integer value can range only between 0 and 1 and also

known as mutex locks, as they are locks that provide mutual exclusion• Binary semaphores used in CS for multiple processesshare a semaphore,

mutex, initialized to 1 is organized

12Loganatahn R, CSE, HKBKCE

do {waiting(mutex);

// critical sectionsignal(mutex);

// remaindersection}while (TRUE);

Page 13: 6 Synchronisation

• Counting semaphores can be used to control access to a resource consisting ofa finite number of instances.

• The semaphore is initialized to the number of resources available.• Process that use a resource performs a wait() (decrementing S) and releases a

resource performs a signal () (incrementing S)• When the count for the semaphore goes to 0, all resources are being used.

After that, processes that wish to use a resource will block until the countbecomes greater than 0.

5.2 Implementation

5. Semaphores Contd…

5.2 Implementation• The disadvantage of the semaphore is it requires busy waiting i.e. while a

process is in its CS, other process that tries to enter its CS must loopcontinuously(wastes CPU cycles)

• This type of semaphore is also called a spinlock because the process "spins"while waiting for the lock(Advantage : no context switch)

• To overcome busy waiting, the definition of wait () and signal () are modified• When semaphore value is not positive the process can blocks itself by block()

operation, which moves process to waiting queue and restarted by a wakeup ()operation when some other process executes a signal() operation

13Loganatahn R, CSE, HKBKCE

Page 14: 6 Synchronisation

• To implement semaphores under this definitiontypedef struct {

int value;struct process *list;

} semaphore;• Implementation of wait():

wait(semaphore *S) {S->value --;if (S->value < 0) {

//add this process to S->list;

5. Semaphores Contd…

//add this process to S->list;block();

}}

• Implementation of signal:signal(semaphore *S) {

S->value++;if (S->value <= 0) {

remove a process P from S->list;wakeup(P);

}} 14Loganatahn R, CSE, HKBKCE

Page 15: 6 Synchronisation

5.3 Deadlock and Starvation• Deadlock – two or more processes are waiting indefinitely for an

event that can be caused by only one of the waiting processes• Let S and Q be two semaphores initialized to 1

P0 P1

wait (S); wait (Q);

wait (Q); wait (S);. .. .. .

5. Semaphores Contd…

. .signal (S); signal (Q);signal (Q); signal (S);

• When P0 executes wait(Q), it must wait until P1 executes signal(Q).Similarly, when P1 executes wait(S), it must wait until Po executessignal(S)

• These signal () operations cannot be executed, Po and Pi aredeadlocked.

• Starvation – indefinite blocking. A process may never be removedfrom the semaphore queue in which it is suspended.

15Loganatahn R, CSE, HKBKCE

Page 16: 6 Synchronisation

• Large class of concurrency-control problems which are used for testing nearlyevery newly proposed synchronization scheme.– Bounded-Buffer Problem– Readers and Writers Problem– Dining-Philosophers Problem

6.1 Bounded-Buffer Problem• N buffers, each can hold one item• Semaphore mutex initialized to the value 1 to provide mutual exclusion for

accesses to the buffer• Semaphore full initialized to the value 0

6. Classical Problems of Synchronization

• Semaphore full initialized to the value 0• Semaphore empty initialized to the value N.

16Loganatahn R, CSE, HKBKCE

The structure of the producer processdo{

// produce an itemwait (empty);wait (mutex);

// add the item to the buffersignal (mutex);signal (full);

} while (true) ;

The structure of the consumer processdo{

wait (full);wait (mutex);

// remove an item from buffersignal (mutex);signal (empty);

// consume the removed item} while (true) ;

Page 17: 6 Synchronisation

6. Classical Problems of Synchronization Contd..

6.2 Readers-Writers Problem• A database is shared among a number of concurrent processes

– Readers – only read the data set; they do not perform any updates– Writers – can both read and write.

• Problem –• first readers-writers problem, requires that, no reader will be kept

waiting unless a writer has already obtained permission to use.• second readers-writers problem, requires that, once a writer is ready,

that writer performs its write as soon as possible

17Loganatahn R, CSE, HKBKCE

that writer performs its write as soon as possible• That is allow multiple readers to read at the same time. Only one

single writer can access the shared data at the same time.• Solution to first readers-writers problem Shares the following data

– Semaphore mutex initialized to 1.– Semaphore wrt initialized to 1.– Integer readcount initialized to 0.

The structure of a writer processwhile (true) {

wait (wrt) ;// writing is performed

signal (wrt) ;}

Page 18: 6 Synchronisation

The structure of a reader processdo {

wait(mutex);readcount + + ;if (readcount == 1)

6. Classical Problems of Synchronization Contd..

• If a writer is in the critical section and n readers are waiting, then onereader is queued on wrt, and n - 1 readers are queued on mutex.

• When a writer executes signal (wrt), It may resume the execution ofeither the waiting readers or a single waiting writer

if (readcount == 1)wait(wrt);

signal(mutex);// reading is performedwait (mutex);readcount --;if (readcount == 0)

signal(wrt);signal(mutex);

}while (TRUE);

18Loganatahn R, CSE, HKBKCE

Page 19: 6 Synchronisation

6.3 The Dining-Philosophers Problem

• A large class of concurrency-control problem i.e. It is a simplerepresentation of the need to allocate several resources among severalprocesses in a deadlock-free and starvation-free manner

• Five philosophers who spend their lives thinking and eating share acircular table surrounded by five chairs and In the center of the table isa bowl of rice, and the table is laid with five single chopsticks

• From time to time, a philosopher gets hungry and tries to pick up the 2

6. Classical Problems of Synchronization Contd..

• From time to time, a philosopher gets hungry and tries to pick up the 2chopsticks that are between him and his left and right neighbors)

19Loganatahn R, CSE, HKBKCE

• A philosopher may pick up only onechopstick at a time, he cannot pick up achopstick that is already in the hand of aneighbor.

• When a hungry philosopher has both hischopsticks at the same time, he eatswithout releasing his chopsticks untilfinished eating

Page 20: 6 Synchronisation

6. Classical Problems of Synchronization Contd..

• Simple solution is to represent each chopstick with a semaphoresemaphore chopstick[5]; and all are initialized to 1

• A philosopher tries to grab a chopstick by executing a wait () operation on thatsemaphore

• A philosopher releases the chopsticks by executing the signal() operation onthe appropriate semaphores

The structure of philosopher Pi

do {wait (chopstick [i] ) ;

• It could create a deadlock i.e. if all fivephilosophers become hungrysimultaneously and each grabs leftchopstick making all the chopstick[ ] equal

20Loganatahn R, CSE, HKBKCE

wait (chopstick [i] ) ;wait(chopstick [ (i + 1) % 5] ) ;

// eatsignal(chopstick [i]);signal(chopstick [(i + 1) % 5]);

/ / think}while (TRUE);

chopstick making all the chopstick[ ] equalto 0, which delays to grab right chopstickforever.

• Several possible remedies- Allow at most four philosophers to be sitting

simultaneously at the table.- Allow a philosopher to pick up her

chopsticks only if both chopsticks areavailable

- Allow an odd philosopher to pick up first left chopstick and then right chopstick,whereas an even philosopher picks up right chopstick and then left chopstick

Page 21: 6 Synchronisation

7. Monitors• Incorrect use of semaphore operations:1. Interchanges the order of wait() and signal () signal(mutex);

//critical sectionwait(mutex);

2. replaces signal (mutex) with wait (mutex) wait(mutex);//critical section

wait(mutex);3. omits the wait (mutex), or the signal (mutex), or bothTo deal with such errors, researchers have developed high-level languagesynchronization construct called the monitor type

21Loganatahn R, CSE, HKBKCE

synchronization construct called the monitor type

7.1 Usage• A type, or abstract data type, encapsulates private data with public methods

to operate on that data• Presents a set of programmer-defined operations that are provided mutual

exclusion within the monitor• A procedure defined within a monitor can access only those variables declared

locally within the monitor and its formal parameters• Only one process may be active within the monitor at a time• The syntax of a monitor is shown

Page 22: 6 Synchronisation

7. Monitors Contd…

monitor monitor-name{

// shared variable declarationsprocedure P1 (…) { …. }procedure P2 (…) { …. }

…procedure Pn (…) {……}

Initialization code ( ….) { … }…

Syntax of a monitor Schematic view of a monitor

22Loganatahn R, CSE, HKBKCE

…}

• Additional synchronizationmechanisms are provided inmonitor by the conditionconstruct which define oneor more variables of typecondition

condition x, y;

Page 23: 6 Synchronisation

7. Monitors Contd…

Monitor with Condition Variables

• The only operations that can be invoked on a condition variable are wait () andsignal()

• x.wait() means that the process invoking this operation is suspended untilanother process invokes x.signal() which resumes (if any) exactly onesuspended process;

23Loganatahn R, CSE, HKBKCE

Page 24: 6 Synchronisation

monitor DP

7. Monitors Contd…

7.2 Dining-Philosophers Solution Using Monitors• Philosopher i can set the variable state[i] = eating only if two neighbors are not

eating: (state[(i+4)%5] != eating) and (state[(i+1) % 5] != eating)• philosopher i must invoke the operations pickup() and putdown() in the

following sequence: DP.pickup(i);eatDP.putdown(i);

• This solution will ensure that there is NO deadlocks but starvation may occurmonitor DP{

enum {THINKING, HUNGRY, EATING}state [5] ;condition self [5];void pickup (int i) {

state[i] = HUNGRY;test(i);if (state[i] != EATING) self [i].wait;

}void putdown (int i) {

state[i] = THINKING;// test left and right neighbors

test((i + 4) % 5);test((i + 1) % 5);

}24Loganatahn R, CSE, HKBKCE

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() {for (int i = 0; i < 5; i++)state[i] = THINKING;

}}

Page 25: 6 Synchronisation

7.3 Implementing a Monitor Using Semaphores• Semaphores and Variables

semaphore mutex; // (initially = 1) where processes waiting to enter the monitor waitsemaphore next; // (initially = 0) where processes that are within the monitor and

ready, wait to become the active processint next_count = 0; number of process suspended on next

• Each procedure F will be replaced bywait(mutex);

//body of F;i f (next_count > 0) signal(next)else signal(mutex); to ensure Mutual exclusion within a monitor

7. Monitors Contd…

else signal(mutex); to ensure Mutual exclusion within a monitor• For each condition variable x, Semaphores and Variables

semaphore x_sem; // initially = 0int x_count = 0;

• The operation x.wait can be implemented as:x_count++;if (next_count > 0) signal(next);else signal(mutex);wait(x_sem);x_count--;

25Loganatahn R, CSE, HKBKCE

• The operation x.signal can beimplemented as:

if (x_count > 0) {next_count++;signal(x_sem);wait(next);next_count--;

}

Page 26: 6 Synchronisation

• If several processes are suspended oncondition x, and then x. signal () executedby some process how to determine whichof the suspended processes should beresumed next

• Using FCFS ordering scheme may not beadequate

• Conditional-wait construct can be usedwhich has the form : x.wait(c);

7. Monitors Contd…

monitor ResourceAllocator {boolean busy;condition x;void acquire(int time) {

if (busy) x.wait(time);busy = TRUE;

}void release() {

7.4 Resuming Processes Within a Monitor Semaphores and Variables

which has the form : x.wait(c);c is a priority number or time required tocomplete the process

• For example a process that needs to accessthe resource must observe the followingsequence: R.acquire(t);

access the resource;R.release();

where R is an instance of typeResourceAllocator

26Loganatahn R, CSE, HKBKCE

void release() {busy = FALSE;x.signal();

}Initialization_code() {

busy = FALSE;}

}


Recommended