Process Synchronization
Process Synchronization
• Background
• Producer-Consumer Concept
• Race Condition
• Critical-Section Problem
• Peterson’s Solution
• Synchronization Hardware
• Classic Problems of Synchronization
• Monitors
Objectives
• To present the concept of process synchronization.
• To introduce the critical-section problem, whose solutions
can be used to ensure the consistency of shared data
• To present both software and hardware solutions of the
critical-section problem
• To examine several classical process-synchronization
problems
• To explore several tools that are used to solve process
synchronization problems
Background
• Processes can execute concurrently
• May be interrupted at any time, partially completing execution
• Concurrent access to shared data may result in data
inconsistency
• Maintaining data consistency requires mechanisms to
ensure the orderly execution of cooperating processes.
Producer-Consumer Concept
• The Producer generates data and places it into a shared
buffer.
• The Consumer retrieves data from the buffer and
processes it.
• The challenge is ensuring proper synchronization so that:
• The producer does not overwrite full buffer slots.
• The consumer does not read empty buffer slots.
Race Condition
A race condition in the Producer-Consumer Problem occurs when the
producer and consumer access the shared buffer simultaneously
without proper synchronization, leading to unexpected behavior or
data corruption.
How It Happens:
•The producer is adding data to the buffer.
•The consumer is removing data from the buffer.
•Without synchronization, both might read/write at the same time,
causing incorrect results.
Race Condition
Example Scenario:
Imagine a multi-threaded logging system:
• Producer writes log entries to a shared buffer.
• Consumer reads log entries and saves them to a file.
Race Condition Possibility:
• Producer checks if the buffer has space.
• Before the producer writes, consumer removes an item.
• Now, both producer and consumer believe they have an accurate view, but
their updates interfere.
• This results in lost log entries or inconsistent logging.
Solution to Prevent Race
Condition
1. Mutex Locks: Prevent Simultaneous Access to the Buffer
A mutex (mutual exclusion) lock is used to ensure that only one
thread accesses a shared resource at a time. When a thread locks the
mutex, other threads must wait until it's unlocked before they can
proceed.
How it works:
•The producer locks the mutex before writing data to the buffer.
•If the consumer tries to read at the same time, it must wait until the
mutex is unlocked.
•Once the producer is done writing, it unlocks the mutex, allowing the
consumer to proceed.
Solution to Prevent Race
Condition
2. Semaphores: Control Producer-Consumer Interactions
•A semaphore is a synchronization tool that maintains a count,
controlling how many threads can access a resource simultaneously. It
can be:
•Binary Semaphore (like a Mutex): Allows only one thread at a time.
•Counting Semaphore: Allows multiple threads up to a defined limit.
How it works:
•The producer increases the semaphore value when adding data to
the buffer.
•The consumer decreases it when taking data from the buffer.
•If the semaphore value reaches zero, the consumer must wait until
data is available.
Solution to Prevent Race
Condition
3. Condition Variables: Ensure Producer Waits if Full, Consumer
Waits if Empty
•Condition variables allow threads to wait until a certain condition is
met. They work alongside mutexes to manage synchronization.
How it works:
•If the buffer is full, the producer waits until space is freed.
•If the buffer is empty, the consumer waits for new data.
•Condition variables are signaled when the required condition is met
(e.g., when space becomes available for the producer).
Critical Section Problem
The Critical Section Problem in an operating system (OS)
occurs when multiple processes or threads share a common
resource, and improper synchronization can lead to race
conditions, data corruption, or unpredictable behavior.
Key Concepts of the Critical Section Problem
•Critical Section: A part of the code where a process accesses
shared resources (e.g., variables, memory, files).
•Mutual Exclusion: Ensures that only one process executes in
the critical section at a time.
•Progress: If multiple processes request access, one must be
allowed to enter without unnecessary delays.
•Bounded Waiting: A process should not be stuck
indefinitely, waiting for access.
Critical Section Problem
Example Scenario
•Imagine a banking system where multiple customers access their
accounts simultaneously:
•If two customers withdraw money at the same time, they might read
the same initial balance, leading to incorrect deductions.
•Without proper synchronization, a race condition might cause
overdrawn accounts or incorrect transaction histories.
Solution to Critical-Section Problem
To prevent conflicts, operating systems implement
synchronization techniques like:
•Mutex Locks: Allow only one thread at a time.
•Semaphores: Control access to limited resources.
•Monitors: Use high-level abstraction for managing
synchronization automatically.
•Peterson’s Algorithm: Classic methods ensuring mutual
exclusion without busy waiting.
Peterson’s Algorithm
• Peterson’s Algorithm is a software-based synchronization solution
that ensures mutual exclusion for two processes sharing a critical
section. It prevents race conditions without requiring special
hardware.
Key Concepts of Peterson’s Algorithm:
• Uses two shared variables:
• Flag[]: Indicates if a process wants to enter the critical section.
• Turn: Decides which process gets access first.
• If a process wants to enter, it sets its flag and assigns turn to the
other process.
• If the other process is in the critical section, it waits; otherwise, it
enters safely.
Peterson’s Algorithm
Advantages:
•Ensures mutual exclusion (only one process enters at a time).
•Prevents deadlocks and ensures fairness (each process gets a turn).
•Works without hardware support, making it useful for theoretical
learning.
Limitations:
•Works only for two processes; extending to multiple processes is
difficult.
•Modern systems prefer mutexes, semaphores, or atomic operations
for better efficiency.
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
• Operating systems using this not broadly scalable
• Modern machines provide special atomic hardware
instructions
• Atomic = non-interruptible
• Either test memory word and set value
• Or swap contents of two memory words
Classical Problems of
Synchronization
• Classical problems used to test newly-proposed synchronization
schemes
• Bounded-Buffer Problem
• Readers and Writers Problem
• Dining-Philosophers Problem
Bounded Buffer Problem (Producer-
Consumer Problem)
1. Bounded Buffer Problem (Producer-Consumer Problem)
•The Bounded Buffer Problem is a synchronization issue where
producers generate data and store it in a finite-sized buffer, while
consumers retrieve the data.
Challenges:
•If the buffer is full, the producer must wait before adding more data.
•If the buffer is empty, the consumer must wait until new data arrives.
•Preventing race conditions, where multiple threads access the buffer
at the same time.
Bounded Buffer Problem (Producer-
Consumer Problem)
Solution:
•Semaphores or Mutex Locks ensure safe access to the buffer.
•Condition Variables allow the producer to wait when full and the
consumer to wait when empty.
•Example: A printing system where documents (producer) are added
to a print queue (buffer), and printers (consumer) process them one by
one.
Readers-Writers Problem
2. Readers-Writers Problem
•The Readers-Writers Problem arises when multiple processes need to
access a shared resource:
•Readers only read the data (non-conflicting).
•Writers modify the data (can cause conflicts).
•Challenges:
•Multiple readers should be allowed to read simultaneously.
•Only one writer should write at a time to prevent data inconsistency.
•Writers should not starve (i.e., always waiting due to continuous
reading).
Readers-Writers Problem
Solution:
•Reader-Writer Locks: Allow multiple readers but restrict access when
a writer modifies the resource.
•Priority-based scheduling: Prevents writer starvation.
• Example: A database system where multiple users (readers) view
records, but only one admin (writer) updates data.
Dining-Philosophers Problem
• Philosophers spend their lives alternating thinking and eating
• Don’t interact with their neighbors, occasionally try to pick up 2 chopsticks
(one at a time) to eat from bowl
• Need both to eat, then release both when done
• In the case of 5 philosophers
• Shared data
• Bowl of rice (data set)
• Semaphore chopstick [5] initialized to 1
Dining-Philosophers Problem Algorithm (Cont.)
• Deadlock handling
•Allow at most 4 philosophers to be sitting simultaneously at
the table.
• Allow a philosopher to pick up the forks only if both are
available (picking must be done in a critical section.
• Use an asymmetric solution -- an odd-numbered philosopher
picks up first the left chopstick and then the right chopstick.
Even-numbered philosopher picks up first the right chopstick
and then the left chopstick.
Dining Philosophers Problem
3. Dining Philosophers Problem
•The Dining Philosophers Problem is a synchronization challenge that models
multiple processes competing for limited resources.
Scenario:
•Imagine five philosophers sitting at a round table with five forks (shared
resources). Each philosopher:
•Thinks when not eating.
•Needs two forks to eat.
•Picks up one fork at a time, creating a risk of deadlock.
•Challenges:
•Deadlock can occur if each philosopher picks up one fork and waits forever
for the second fork.
•Resource starvation if some philosophers never get access to forks.
Dining Philosophers Problem
Solution:
•Using semaphores to control fork access.
•Imposing an ordering rule (e.g., philosophers pick up left fork first,
then right).
•Introducing a waiter (controller process) to regulate resource
allocation.
•Example: A multi-threaded system where different processes
(philosophers) share CPU resources (forks) and must coordinate their
execution.
Monitors
Monitor in Process Synchronization
•A monitor is a high-level synchronization construct in operating
systems that helps manage access to shared resources among multiple
processes or threads without race conditions. It simplifies
concurrency control by using automatic mutual exclusion.
Key Features of Monitors:
•Encapsulation – Shared resources are managed within a monitor,
preventing direct access from external processes.
•Mutual Exclusion – Only one process can execute inside the monitor
at any given time, avoiding conflicts.
•Condition Variables – Monitors provide built-in waiting mechanisms
to handle situations where a resource is not available.
Monitors
How Monitors Work:
•A monitor consists of:
•Procedures – Functions that allow safe access to shared resources.
•Shared Data – Resources that processes interact with.
•Condition Variables – Used for managing process waiting and
signaling.
Monitors
Example: If multiple threads want to withdraw money from a shared
bank account, the monitor ensures that:
•Only one thread withdraws at a time.
•Other threads wait if the balance is too low.
•Once money is deposited, waiting threads are notified.
Condition Variables in Monitors:
•Monitors use two operations to manage waiting processes:
•Wait() – A process waits until a resource becomes available.
•Signal() – A process notifies waiting threads when a resource is ready.
Monitors
Example: In a print queue system, if no documents are ready, the
printer waits. When a user submits a document, the system signals
the printer to start processing.
Advantages of Monitors:
•Automatic Mutual Exclusion – No need for explicit locking
mechanisms like semaphores. ✅ Simplified Synchronization – Handles
waiting and signaling internally. ✅ Deadlock Prevention – Reduces
complex locking scenarios.
End