Os Unit 3
Os Unit 3
A cri cal resource is a shared hardware or so ware component in a computer system that
must not be accessed by more than one process or thread at the same me.
Key Points:
I/O Devices Printer Two print jobs mixing leads to garbage output
Files Log file or config file One write may overwrite another
Databases Bank account records Concurrent updates can lead to wrong balance
CPU Register Shared among threads May lose data if both write at the same me
If cri cal resources are not properly managed, it can lead to:
Deadlocks
Inconsistent outputs
System crashes
Semaphores
Mutexes
Monitors
Locks
Peterson’s Algorithm
Cri cal Sec on – Defini on and Explana on
A cri cal sec on is a part of a program where the process accesses shared resources (like
shared memory, files, or printers) that can be used by only one process at a me.
Why is it Important?
Each process that accesses shared data must follow this pa ern:
css
CopyEdit
Sec on Func on
Entry Sec on Code that requests permission to enter the cri cal sec on
To design correct cri cal sec on handling, three condi ons must be sa sfied:
1. Mutual Exclusion – Only one process in the cri cal sec on at a me.
2. Progress – If no process is in the cri cal sec on, selec on of the next should not be
delayed unnecessarily.
3. Bounded Wai ng – A limit must exist on how long a process waits to enter its cri cal
sec on.
Semaphore: Implementa on and Explana onA semaphore is a synchroniza on tool used in
opera ng systems to control access to cri cal resources and prevent issues like race
condi ons, deadlocks, and inconsistent data.
What is a Semaphore?A semaphore is an integer variable used to signal and control access
between processes. There are two main types:
1. Coun ng Semaphore – Can have any integer value (used for managing a resource
with mul ple instances).
2. Binary Semaphore (Mutex) – Only 0 or 1 (used for mutual exclusion; only one
process at a me).
Opera on Descrip on
signal(S) (also called V(S) or Increments semaphore. If any process is wai ng, it gets
up(S)) unblocked.
CopyEdit
// Define a semaphore
// Wait opera on
// Signal opera on
CopyEdit
semaphore mutex = 1;
Process 1:
Process 2:
This ensures only one process at a me enters the cri cal sec on.
Busy Wai ng (CPU keeps checking): Resolved using blocking semaphores (e.g., in
OS-level implementa on).
Starva on: A process may wait indefinitely if others keep entering first.
Semaphore Advantages:
Goal:
Semaphores Used:
CopyEdit
int buffer[N];
int in = 0, out = 0;
// Producer Process
void producer() {
int item;
while (true) {
item = produce_item(); // Create an item
in = (in + 1) % N;
// Consumer Process
void consumer() {
int item;
while (true) {
out = (out + 1) % N;
}
Readers-Writers Problem (Using Semaphores)
The Readers-Writers Problem is a classic synchroniza on problem that deals with shared
data being accessed by:
Mul ple readers (who only read and do not modify), and
Problem Statement:
Mul ple readers can read simultaneously (no data modifica on).
Only one writer can write at a me (no other writer or reader should be accessing
the data).
Challenges:
Reader Process:
CopyEdit
wait(mutex);
read_count++;
if (read_count == 1)
signal(mutex);
read_data();
// --------------------------
wait(mutex);
read_count--;
if (read_count == 0)
signal(mutex);
Writer Process:
CopyEdit
wait(rw_mutex);
write_data();
// --------------------------
signal(rw_mutex);
Explana on:
Mul ple readers can enter the cri cal sec on at the same me.
Writers must wait un l all readers are done (i.e., read_count == 0).
Drawbacks:
Writer starva on: If readers keep coming, writer may never get a chance.
Variants:
Deadlock is avoided.
Allow only one philosopher to access the monitor (shared logic) at a me.
Key Concepts:
Philosopher States:
CopyEdit
Monitor Structure:
CopyEdit
monitor DiningPhilosophers {
};
CopyEdit
pickup(int i) {
state[i] = HUNGRY;
if (state[i] != EATING)
CopyEdit
putdown(int i) {
state[i] = THINKING;
CopyEdit
test(int i) {
state[(i + 1) % 5] != EATING) {
state[i] = EATING;
Data sharing
Synchroniza on
Event signaling
Resource sharing
Advantage Descrip on
Shared memory IPC can be much faster than other methods (like
5. Efficiency
message passing).
One process (usually the parent or server) creates a shared memory segment using OS
system calls.
In UNIX/Linux: shmget(key, size, IPC_CREAT | permissions);
Processes that want to use the shared memory a ach it to their address space.
The other process reads data from the same memory region.
Example:
4. Synchroniza on:Since mul ple processes may access the shared memory
simultaneously, synchroniza on tools are used to avoid race condi ons:
Semaphores
Mutexes
Monitors
These tools ensure that only one process at a me accesses the shared sec on when
required.
The memory segment can then be deleted using shmctl() with IPC_RMID.
Interprocess Communica on (IPC) on a Single Computer System
On a single computer:
To cooperate (e.g., share results or coordinate execu on), they must communicate
using IPC mechanisms provided by the OS.
Shared Memory Processes share a region of memory for fast data exchange.
Named Pipes
Like pipes but accessible by unrelated processes using a name.
(FIFOs)
Semaphores Used for signaling and synchroniza on, not direct data transfer.
Memory-mapped Map files into memory so that changes by one process are
Files visible to another.
Pipes:
bash
CopyEdit
$ ls | grep ".txt"
Here, the output of ls is piped to grep. This is IPC using anonymous pipes.
CopyEdit
Synchroniza on in IPC:
To prevent conflicts (like two processes wri ng at the same me), IPC is o en paired
with synchroniza on tools like:
Semaphores
Mutexes
Monitors
Condi on variables
Benefit Descrip on
PIPES – Overview
A pipe is a unidirec onal communica on channel that allows data to flow from one
process to another. It's one of the simplest forms of IPC, mainly used for parent-child
process communica on.
In C (UNIX/Linux systems), you can create a pipe using the pipe() system call.
Syntax:
CopyEdit
int fd[2];
pipe(fd);
CopyEdit
int fd[2];
pipe(fd);
if (fork() == 0) {
// Child Process
} else {
// Parent Process
Pipes like this only work between related processes (e.g., parent-child).
A Named Pipe, also called FIFO (First In, First Out), is a special file used for IPC between
unrelated processes.
In Terminal:
bash
CopyEdit
mkfifo mypipe
In C Code:
CopyEdit
Process 1 (Writer):
CopyEdit
close(fd);
Process 2 (Reader):
CopyEdit
int fd = open("mypipe", O_RDONLY);
close(fd);
lua
CopyEdit
| |
| |
| |
close() close()
Feature Benefit
Limita ons:
Unidirec onal: One-way data flow (unless two pipes are used).
A message queue is a method of interprocess communica on (IPC) that allows mul ple
processes to exchange messages using a queue data structure managed by the kernel.
The OS maintains the message queue and ensures ordering and access control.
Purpose:
Messages are stored in the queue un l the receiving process reads them.
Component Descrip on
msg_type Message type (user-defined long integer, used for filtering messages).
*msg_next Pointer to the next message in the queue (linked list structure).
Advantages:
Limita ons:
To efficiently manage this, the kernel maintains internal data structures to:
CopyEdit
struct shmid_ds {
};
Key Fields:
CopyEdit
struct ipc_perm {
};
The kernel maintains an internal table (array or linked list) of all shared memory
segments, each represented by a shmid_ds structure.
Entry No. Key Size (bytes) Creator PID A ach Count
When a process a aches to a shared memory segment using shmat(), the kernel
maps the shared memory into the process's page table.
This allows the process to access the shared region as part of its address space.
1. Crea on: shmget() allocates a segment and creates an entry in the kernel's segment
table (shmid_ds).
2. A achment: shmat() maps the segment into the process’s address space;
shm_na ch is incremented.
5. Dele on: shmctl(..., IPC_RMID, ...) marks the segment for removal once all processes
detach.
The kernel does not provide built-in locking for shared memory.
Summary Table: