Operating
Systems
Process Synchronization
Process
Synchronization
 Concurrent access to shared
data may result in data
inconsistency.
 Maintaining data consistency
requires mechanisms to ensure
that cooperating processes
access shared data
sequentially.
Bounded-Buffer Problem
Shared data
#define BUFFER_SIZE 10
typedef struct {
. . .
} item;
item buffer[BUFFER_SIZE];
int in = 0, out = 0;
int counter = 0;
Producer process
item nextProduced;
…
while (1) {
while (counter == BUFFER_SIZE) ;
buffer[in] = nextProduced;
in = (in + 1) % BUFFER_SIZE;
counter++;
}
Bounded-Buffer Problem
Bounded-Buffer Problem
Consumer process
item nextConsumed;
while (1) {
while (counter == 0) ;
nextConsumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
counter--;
}
 “counter++” in assembly language
MOV R1, counter
INC R1
MOV counter, R1
 “counter--” in assembly language
MOV R2, counter
DEC R2
MOV counter, R2
Bounded-Buffer Problem
 If both the producer and consumer
attempt to update the buffer
concurrently, the machine language
statements may get interleaved.
 Interleaving depends upon how the
producer and consumer processes
are scheduled.
Bounded-Buffer Problem
 Assume counter is initially 5. One
interleaving of statements is:
producer: MOV
INC
R1, counter
R1
(R1 = 5)
(R1 = 6)
consumer: MOV
DEC
R2, counter
R2
(R2 = 5)
(R2 = 4)
producer: MOV counter, R1 (counter = 6)
consumer: MOV counter, R2 (counter = 4)
 The value of count may be either 4 or 6,
where the correct result should be 5.
Bounded-Buffer Problem
 Race Condition: The situation
where several processes access
and manipulate shared data
concurrently, the final value of the
data depends on which process
finishes last.
Process
Synchronization
 Critical Section: A piece of code
in a cooperating process in which
the process may updates shared
data (variable, file, database, etc.).
 Critical Section Problem:
Serialize executions of critical
sections in cooperating processes
Process
Synchronization
 More Examples
Bank transactions
Airline reservation
Process
Synchronization
Bank Transactions
Balance
Deposit Withdrawal
MOV A, Balance
ADD A, Deposited
MOV Balance, A
MOV B, Balance
SUB B, Withdrawn
MOV Balance, B
D W
 Bank Transactions
Current balance = Rs. 50,000
Check deposited = Rs. 10,000
ATM withdrawn = Rs. 5,000
Bank Transactions
Bank Transactions
Check Deposit:
MOV A, Balance
ADD A, Deposit ed
ATM Withdrawal:
MOV B, Balance
SUB B, Withdrawn
Check Deposit:
MOV Balance, A
ATM Withdrawal:
MOV Balance, B
// A = 50,000
// A = 60,000
// B = 50,000
// B = 45,000
// Balance = 60,000
// Balance = 45,000
Diagram of Critical Section Problem
P0 P1 Pn-1
Shared
Data
• Each process Pi has its own critical section
• Accesses to shared data only in CS
• Lock – will consider later
• In shared data, accessible by all
• Often 1 lock for all n processes
• Guards access to all critical sections
• Ensures mutual exclusivity
. . .
 Software based solutions
 Hardware based solutions
 Operating system based
solution
Solution of the Critical Problem
 Software based solutions
 Hardware based solutions
 Operating system based
solution
Solution of the Critical Problem
do {
critical section
remainder section
} while (1);
entry section
exit section
Structure of Solution
Solution to Critical- Section Problem
 2-Process Critical Section Problem
 N-Process Critical Section Problem
 Conditions for a good solution:
1. Mutual Exclusion: If a process is
executing in its critical section, then
no other processes can be executing
in their critical sections.
Solution to Critical- Section Problem
2. Progress: If no process is
executing in its critical section and
some processes wish to enter their
critical sections, then only those
processes that are not executing in
their remainder sections can
decide which process will enter its
critical section next, and this
decision cannot be postponed
indefinitely.
Solution to Critical- Section Problem
3. Bounded Waiting: A bound must
exist on the number of times that
other processes are allowed to
enter their critical sections after a
process has made a request to
enter its critical section and before
that request is granted.
Possible Solutions
 Only 2 processes, P0 and P1
 Processes may share some common
variables to synchronize their actions.
 General structure of process Pi
do {
critical section
remainder section
} while (1);
entry section
exit section
Peterson’s Algorithm
 Combined shared variables of
algorithms 1 and 2.
 boolean flag[2]; // Set to false
 int turn=0;
Peterson’s Algorithm
 Process Pi
do {
critical section
remainder section
} while (1);
flag[ i ] = true;
turn = j;
while (flag[ j ] && turn == j);
flag[ i ] = false;
Peterson’s Algorithm
 Meets all three requirements:
Mutual Exclusion: ‘turn’ can have
one value at a given time (0 or 1)
Bounded-waiting: At most one
entry by a process and then the
second process enters into its
CS
Peterson’s Algorithm
 Progress: Exiting process sets
its ‘flag’ to false … comes back
quickly and set it to true again
… but sets turn to the number
of the other process
Synchronization Hardware
 Many systems provide hardware support for implementing the critical section
code.
 All solutions below based on idea of locking
 Protecting critical regions via locks
 Uniprocessors – could disable interrupts
 Currently running code would execute without preemption
 Generally too inefficient on multiprocessor systems
 Modern machines provide special atomic hardware instructions
 Atomic = non-interruptible
 test_and_set instruction
 test memory word and set value
 compare_and_swap instruction
 swap contents of two memory words
Solution to Critical-section Problem
Using Locks
while (true) {
acquire lock
critical section
release lock
remainder section
}
test_and_set Instruction
Definition:
boolean test_and_set (boolean *target)
{
boolean rv = *target;
*target = true;
return rv;
}
1. Executed atomically – cannot be interrupted in the middle
2. Returns the original value of passed parameter
3. Set the new value of passed parameter to true.
Solution using test_and_set()
 Shared Boolean variable lock
 initialized lock = false
 unlocked initially
while (true) {
while (test_and_set(&lock));
/* critical section */
lock = false;
/* remainder section */
}
 Is the test_and_set()-based solution good?
 No
 Mutual Exclusion: Satisfied
 Progress: Satisfied
 Bounded Waiting: Not satisfied
Solution with test_and_set()
Bounded-waiting Mutual Exclusion with test_and_set
 The common data structures:
 boolean waiting[n];
 // initialized to false
 boolean lock;
 // initialized to false
Swaps atomically
int compare and swap(int *value, int expected,
int new value)
{
int temp = *value;
if (*value == expected)
*value = new value;
return temp;
}
compare and swap Instruction
Structure for Pi
Solution with compare and swap
while (true) {
while (compare and swap(&lock, 0, 1) != 0);
/* critical section */
lock = 0;
/* remainder section */
}
 Is the swap-based solution good?
 No
 Mutual Exclusion: Satisfied
 Progress: Satisfied
 Bounded Waiting: Not satisfied
Solution with compare and swap
Bounded-waiting mutual exclusion with
compare and swap().
‘key’ local; ‘lock’
and ‘waiting’
global
All variables set
to false
Mutex Locks
 Previous solutions are complicated and generally inaccessible to application
programmers
 OS designers build software tools to solve critical section problem
 Simplest is mutex lock
 Boolean variable indicating if lock is available or not
 Protect a critical section by
 First acquire() a lock
 Then release() the lock
 Calls to acquire() and release() must be atomic
 Usually implemented via hardware atomic instructions such as compare-and-swap.
 But this solution requires busy waiting
 This lock therefore called a spinlock
Solution to CS Problem Using Mutex Locks
while (true) {
acquire lock
critical section
release lock
remainder section
}
acquire() {
while (!available)
; /* busy wait */
available = false;
}
release() {
available = true;
}
The common data
boolean available;
// initialized to True
Semaphores
 Synchronization tool
 Available in operating systems
 Semaphore S – integer variable that
can only be accessed via two
indivisible (atomic) operations, called
wait and signal
n-Processes CS Problem
 Shared data:
 semaphore mutex = 1;
 Structure of Pi:
do {
critical section
remainder section
} while (1);
wait(mutex);
signal(mutex);
Is it a Good Solution?
 Mutual Exclusion: Yes
 Progress:Yes
 Bounded Waiting: No
Semaphore Implementation
typedef struct {
int value;
struct process *list;
} semaphore;
Now, the wait() semaphore operation can
be defined as
wait(semaphore *S) {
S->value--;
if (S->value < 0) {
add this process to S->list;
sleep();
}
}
signal() semaphore operation
can be defined as
signal(semaphore *S) {
S->value++;
if (S->value <= 0) {
remove a process P from S->list;
wakeup(P);
}
}

Synchronization in os.pptx

  • 1.
  • 2.
    Process Synchronization  Concurrent accessto shared data may result in data inconsistency.  Maintaining data consistency requires mechanisms to ensure that cooperating processes access shared data sequentially.
  • 3.
    Bounded-Buffer Problem Shared data #defineBUFFER_SIZE 10 typedef struct { . . . } item; item buffer[BUFFER_SIZE]; int in = 0, out = 0; int counter = 0;
  • 4.
    Producer process item nextProduced; … while(1) { while (counter == BUFFER_SIZE) ; buffer[in] = nextProduced; in = (in + 1) % BUFFER_SIZE; counter++; } Bounded-Buffer Problem
  • 5.
    Bounded-Buffer Problem Consumer process itemnextConsumed; while (1) { while (counter == 0) ; nextConsumed = buffer[out]; out = (out + 1) % BUFFER_SIZE; counter--; }
  • 6.
     “counter++” inassembly language MOV R1, counter INC R1 MOV counter, R1  “counter--” in assembly language MOV R2, counter DEC R2 MOV counter, R2 Bounded-Buffer Problem
  • 7.
     If boththe producer and consumer attempt to update the buffer concurrently, the machine language statements may get interleaved.  Interleaving depends upon how the producer and consumer processes are scheduled. Bounded-Buffer Problem
  • 8.
     Assume counteris initially 5. One interleaving of statements is: producer: MOV INC R1, counter R1 (R1 = 5) (R1 = 6) consumer: MOV DEC R2, counter R2 (R2 = 5) (R2 = 4) producer: MOV counter, R1 (counter = 6) consumer: MOV counter, R2 (counter = 4)  The value of count may be either 4 or 6, where the correct result should be 5. Bounded-Buffer Problem
  • 9.
     Race Condition:The situation where several processes access and manipulate shared data concurrently, the final value of the data depends on which process finishes last. Process Synchronization
  • 10.
     Critical Section:A piece of code in a cooperating process in which the process may updates shared data (variable, file, database, etc.).  Critical Section Problem: Serialize executions of critical sections in cooperating processes Process Synchronization
  • 11.
     More Examples Banktransactions Airline reservation Process Synchronization
  • 12.
    Bank Transactions Balance Deposit Withdrawal MOVA, Balance ADD A, Deposited MOV Balance, A MOV B, Balance SUB B, Withdrawn MOV Balance, B D W
  • 13.
     Bank Transactions Currentbalance = Rs. 50,000 Check deposited = Rs. 10,000 ATM withdrawn = Rs. 5,000 Bank Transactions
  • 14.
    Bank Transactions Check Deposit: MOVA, Balance ADD A, Deposit ed ATM Withdrawal: MOV B, Balance SUB B, Withdrawn Check Deposit: MOV Balance, A ATM Withdrawal: MOV Balance, B // A = 50,000 // A = 60,000 // B = 50,000 // B = 45,000 // Balance = 60,000 // Balance = 45,000
  • 15.
    Diagram of CriticalSection Problem P0 P1 Pn-1 Shared Data • Each process Pi has its own critical section • Accesses to shared data only in CS • Lock – will consider later • In shared data, accessible by all • Often 1 lock for all n processes • Guards access to all critical sections • Ensures mutual exclusivity . . .
  • 16.
     Software basedsolutions  Hardware based solutions  Operating system based solution Solution of the Critical Problem
  • 17.
     Software basedsolutions  Hardware based solutions  Operating system based solution Solution of the Critical Problem
  • 18.
    do { critical section remaindersection } while (1); entry section exit section Structure of Solution
  • 19.
    Solution to Critical-Section Problem  2-Process Critical Section Problem  N-Process Critical Section Problem  Conditions for a good solution: 1. Mutual Exclusion: If a process is executing in its critical section, then no other processes can be executing in their critical sections.
  • 20.
    Solution to Critical-Section Problem 2. Progress: If no process is executing in its critical section and some processes wish to enter their critical sections, then only those processes that are not executing in their remainder sections can decide which process will enter its critical section next, and this decision cannot be postponed indefinitely.
  • 21.
    Solution to Critical-Section Problem 3. Bounded Waiting: A bound must exist on the number of times that other processes are allowed to enter their critical sections after a process has made a request to enter its critical section and before that request is granted.
  • 22.
    Possible Solutions  Only2 processes, P0 and P1  Processes may share some common variables to synchronize their actions.  General structure of process Pi do { critical section remainder section } while (1); entry section exit section
  • 23.
    Peterson’s Algorithm  Combinedshared variables of algorithms 1 and 2.  boolean flag[2]; // Set to false  int turn=0;
  • 24.
    Peterson’s Algorithm  ProcessPi do { critical section remainder section } while (1); flag[ i ] = true; turn = j; while (flag[ j ] && turn == j); flag[ i ] = false;
  • 25.
    Peterson’s Algorithm  Meetsall three requirements: Mutual Exclusion: ‘turn’ can have one value at a given time (0 or 1) Bounded-waiting: At most one entry by a process and then the second process enters into its CS
  • 26.
    Peterson’s Algorithm  Progress:Exiting process sets its ‘flag’ to false … comes back quickly and set it to true again … but sets turn to the number of the other process
  • 27.
    Synchronization Hardware  Manysystems provide hardware support for implementing the critical section code.  All solutions below based on idea of locking  Protecting critical regions via locks  Uniprocessors – could disable interrupts  Currently running code would execute without preemption  Generally too inefficient on multiprocessor systems  Modern machines provide special atomic hardware instructions  Atomic = non-interruptible  test_and_set instruction  test memory word and set value  compare_and_swap instruction  swap contents of two memory words
  • 28.
    Solution to Critical-sectionProblem Using Locks while (true) { acquire lock critical section release lock remainder section }
  • 29.
    test_and_set Instruction Definition: boolean test_and_set(boolean *target) { boolean rv = *target; *target = true; return rv; } 1. Executed atomically – cannot be interrupted in the middle 2. Returns the original value of passed parameter 3. Set the new value of passed parameter to true.
  • 30.
    Solution using test_and_set() Shared Boolean variable lock  initialized lock = false  unlocked initially while (true) { while (test_and_set(&lock)); /* critical section */ lock = false; /* remainder section */ }
  • 31.
     Is thetest_and_set()-based solution good?  No  Mutual Exclusion: Satisfied  Progress: Satisfied  Bounded Waiting: Not satisfied Solution with test_and_set()
  • 32.
    Bounded-waiting Mutual Exclusionwith test_and_set  The common data structures:  boolean waiting[n];  // initialized to false  boolean lock;  // initialized to false
  • 33.
    Swaps atomically int compareand swap(int *value, int expected, int new value) { int temp = *value; if (*value == expected) *value = new value; return temp; } compare and swap Instruction
  • 34.
    Structure for Pi Solutionwith compare and swap while (true) { while (compare and swap(&lock, 0, 1) != 0); /* critical section */ lock = 0; /* remainder section */ }
  • 35.
     Is theswap-based solution good?  No  Mutual Exclusion: Satisfied  Progress: Satisfied  Bounded Waiting: Not satisfied Solution with compare and swap
  • 36.
    Bounded-waiting mutual exclusionwith compare and swap(). ‘key’ local; ‘lock’ and ‘waiting’ global All variables set to false
  • 37.
    Mutex Locks  Previoussolutions are complicated and generally inaccessible to application programmers  OS designers build software tools to solve critical section problem  Simplest is mutex lock  Boolean variable indicating if lock is available or not  Protect a critical section by  First acquire() a lock  Then release() the lock  Calls to acquire() and release() must be atomic  Usually implemented via hardware atomic instructions such as compare-and-swap.  But this solution requires busy waiting  This lock therefore called a spinlock
  • 38.
    Solution to CSProblem Using Mutex Locks while (true) { acquire lock critical section release lock remainder section } acquire() { while (!available) ; /* busy wait */ available = false; } release() { available = true; } The common data boolean available; // initialized to True
  • 39.
    Semaphores  Synchronization tool Available in operating systems  Semaphore S – integer variable that can only be accessed via two indivisible (atomic) operations, called wait and signal
  • 40.
    n-Processes CS Problem Shared data:  semaphore mutex = 1;  Structure of Pi: do { critical section remainder section } while (1); wait(mutex); signal(mutex);
  • 41.
    Is it aGood Solution?  Mutual Exclusion: Yes  Progress:Yes  Bounded Waiting: No
  • 42.
    Semaphore Implementation typedef struct{ int value; struct process *list; } semaphore;
  • 43.
    Now, the wait()semaphore operation can be defined as wait(semaphore *S) { S->value--; if (S->value < 0) { add this process to S->list; sleep(); } }
  • 44.
    signal() semaphore operation canbe defined as signal(semaphore *S) { S->value++; if (S->value <= 0) { remove a process P from S->list; wakeup(P); } }