IPC - ST

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 95

Processes & Threads

InterProcess Communication (IPC)


Review
• Process Model
– Pseudo-parallelism (Multi-programming, quantum or time slice)
– Context Switch (user mode  kernel mode, switch CPU to other
process – load/store PCB)
– Scheduling algorithm
• PCB
– Id, registers, scheduling information, memory management
information, accounting information, I/O status information, …
– State (New, Running, Ready, Blocked, Terminal)
• CPU Utilization
– Shows the CPU utilization
– 1 – pn
Review
• Threads
– Share the same address space and resources of the process
– Each thread has its own PC, registers and stack of execution
– There is no protection between threads in one process
– Have its own stack
®Improve context switch among processes, optimize quantum
– Are implemented in 3 modes: user, kernel, hybrid
Objectives…
• Interprocess communication
– Overview
– Race Conditions
– Critical Regions
– Mutual Exclusion with Busy Waiting
– Disable Interrupts
– Lock Variables
– Strict Alternative
– Peterson’s solution
– TSL instructions
– Sleep and wakeup
– Semaphores
– Mutexes
– Monitors
– Message Passing
– Barries
InterProcess Communication (IPC)
Overview
• How one process can pass information to another?
• Make sure two or more processes do not get in each
other’s way
• Proper sequencing when dependencies are present: if
process A produces data and process B prints them, B has
to wait until A has produced some data before starting to
print
• Context
– Why does the C/ C++ compiler resist the back door pointer?
– Why do the objects give the shallow (pass/return by reference)
or deep copy (pass/return by value) way to implement it?
InterProcess Communication (IPC)
Race Conditions
• A situation where several threads (or processes) manipulate the same (shared)
data concurrently and the outcome of the execution depends on the precise
order of what is happening when, is called a race condition (đk tranh chấp)
• Ex

Tanenbaum, Fig. 2-21.

• Other example in practically


– The bank account has the balance as 800, and can withdraw with 2 ATM cards at
different 2 locations at a time
– First, the user1 pushes card to ATM machine and checking account’s balance. The
process P1 is created simultaneously in server. Then the checking result is 800. The
user choose withdrawing 400
– Second, in the other location, the user2 also do same things as user1 and process P2 is
created. The user choose withdrawing 500
– In the case, if the P1 is out of time slice, the P2 is served first then user 2 gets 500.
Later, does the user1 get 400 or get the error message?
• The final state of a resource is unpredictable and could be inconsistent
09/17/2023 Module A - Introduction 8/40
09/17/2023 Module A - Introduction 9/40
Problem
InterProcess Communication (IPC)
Critical Regions
• The part of program where the shared memory is accessed (The
code regions where race conditions appear)
• Are the areas of code whose execution must be regulated (điều
chỉnh) to guarantee predictable results
• To avoid races, we could arrange matters such that no two
processes were ever in their critical regions
• Conditions required to avoid race condition:
– No two processes may be simultaneously inside their critical regions.
– No assumptions may be made about speeds or the number of CPUs.
– No process running outside its critical region may block other processes.
– No process should have to wait forever to enter its critical region.

Tanenbaum, Fig. 2-22.


InterProcess Communication (IPC)
Mutual Exclusion with Busy Waiting
• Mutual Exclusion
– If one thread is executing in its critical section, no other threads
can be executing in their critical sections (Only one process can
use a shared resource at one moment)
• Proposals for achieving mutual exclusion: (các giải pháp đồng bộ - synchronous solutions)

– Disabling interrupts (tắt ngắt) – giải pháp phần cứng


– Lock variables (cờ hiệu): cửa mở thì vào được; vào rồi, chưa kịp đóng thì đối tượng khác vào được.
– Strict alternation (luân phiên): tới lượt - làm xong – chuyển lượt
– Peterson's solution: kết hợp cờ hiệu và luân phiên
– The TSL instruction (giải pháp phần cứng – đóng gói cờ hiệu)
– Sleep and Wakeup
– Producer & Consumer (problem)
– Semaphore, Mutex, Monitor
– Barrier
InterProcess Communication (IPC)
A study problem
Time Person A Person B
3:00 Look in fridge. Run out of milk.
3:05 Go to the store.
3:10 Arrive at store. Look in fridge. Run out of milk.
3:15 Buy milk. Go to the store.
3:20 Arrive home, put milk away. Arrive at store.
3:25 Buy milk.
3:30 Arrive home, put milk away.
Not a good cooperation => Too much milk.

• Correctness requirements
– Never more than one person buys milk (First Rule)
– Someone buys if needed (Fourth Rule)
• This solution of this case (mutual exclusion) is called an
synchronization
InterProcess Communication (IPC)
Disabling Interrupts
• On a single-processor system, each process
– Disable all interrupts just after entering its critical region
– Re-enable them just before leaving it
 A process can examine and updated shared memory
without fear that any other process will intervene
• Disadvantages
– Give user processes the power to turn off interrupts (if a process
dies while it is in its critical region → the system is indefinitely
blocked)
– On a multiprocessor, the disabling interrupts affects only the
CPU that executed the disable instruction while the other ones
will continue running and can access the shared memory
 Disabling interrupts is often a useful technique within
the OS itself but is not appropriate for user processes
InterProcess Communication (IPC)
Lock Variables
while(TRUE) {
while (lock == 1); //waiting until lock sets to 0
lock = 1;
critical_region();
lock = 0;
nonCritical_region();
}
Process 1 Process 2
while(TRUE) { while(TRUE) {
while (lock == 1); while (lock == 1);
lock = 1; lock = 1;
critical_region(); critical_region();
lock = 0; lock = 0;
nonCritical_region(); nonCritical_region();
} }
InterProcess Communication (IPC)
Lock Variables
• The solution fails
occasionally
– both processes can be
simultaneously in their own
critical regions
• Process A reads the lock and
sees that it is 0
• Before it can set the lock to 1,
Process B is scheduled, run,
and set the clock to 1 (then
Process A set the clock to 1)
• Testing a variable until
some value appears is called
busy waiting (wastes CPU
time)
InterProcess Communication (IPC)
Strict Alternation

Tanenbaum, Fig. 2-23.

• The two processes strictly alternate in entering their


critical regions
• Problems
– Testing a variable until some value appears is called busy
waiting (wastes CPU time)
– A process is being blocked by another process not in its critical
region
• One of processes is much slower than the other
• When one process dies, the other ones are blocked forever
InterProcess Communication (IPC)
Peterson’s Solution

Tanenbaum, Fig. 2-24.

• Combines the idea of taking turns with the idea of lock


variables and strict alternation
InterProcess Communication (IPC)
Peterson’s Solution
• Solution for process Pi
do {
enter_region(i);
critical_region();
leave_region(i);
nonCritical_region();
} while (TRUE);
• Mutual exclusion is preserved (1st rule)
– Pi enters its critical section only if either interested [j]=false or turn=j.
– If both processes want to enter their critical sections at the same time, then
interested [i] = interested [j] = true.
– However, the value of turn can be either 0 or 1 but cannot be both. Hence, one
of the processes must have successfully executed the while statement (to enter
its critical section), and the other process has to wait, till the process leaves its
critical section → mutual exclusion is preserved.
InterProcess Communication (IPC)
Peterson’s Solution
• The 3rd rule is satisfied.
– Case 1:
• Pi is ready to enter its critical section.
• If Pj is not ready to enter the critical section (it is in the remainder section).
• Then interested[j] = false, and Pi can enter its critical section.
– Case 2:
• Pi and Pj are both ready to enter its critical section.
• interested[i] = interested [j] = true. And Either turn = i or turn = j.
• If turn = i, then Pj will enter the critical section.
• If turn = j, then Pi will enter the critical section
• The 4th rule is met
– Once Pj exits its critical section, it will reset interested [j] to false, allowing Pi to
enter its critical section.
– Even if Pj immediately resets interested [j] to true, it must also set turn to i.
– Then, Pi will enter the critical section after at most one entry by Pj.
InterProcess Communication (IPC)
The TSL (Test and Set Lock) Instruction
• Instruction form: TSL RX, LOCK
– Reads the content of the memory word lock into register RX
– Stores a nonzero value at the memory address lock (sets to 1)
– Both 2 above steps are made atomically (indivisible – no processor can access
memory word until the instruction is finished)
• Different from Disabling interrupts: disabling interrupts then performing a read
on a memory word followed by a write does not prevent a second processor on
the bus from accessing the word between the read and the write
• Solution: Each process calls
– enter_region before entering its critical region
– leave_region after leaving its critical region
enter_region: leave_region:
TSL REG, LOCK MOVE LOCK, #0
CMP REG, #0 RET Tanenbaum, Fig. 2-25.
JNE enter_region
RET
• TSL solution uses a lock variable. When lock is 0, a process using TSL to set lock
to 1 and access the critical region. When it finishes, it set lock to 0
InterProcess Communication (IPC)
The TSL (Test and Set Lock) Instruction
• Mutual exclusion is preserved (1st rule)
– When a process leaves its critical section, lock is set to 0
• The 3rd rule is satisfied.
– A process exiting the critical section either sets lock to 1
– Both allow a process that is waiting to enter its critical section to
proceed
• The 4th rule is met
– The implementation of process same as Peterson (using array to
mark)
• The TSL can be alternated same with XCHG instruction
on Intel x86 CPU
– The XCHG exchange the content locations atomically
09/17/2023 Module A - Introduction 29/40
09/17/2023 Module A - Introduction 30/40
09/17/2023 Module A - Introduction 33/40
09/17/2023 Module A - Introduction 35/40
SOLUTIONS “SLEEP AND WAKEUP”

* Semaphore
* Monitor
* Mutexes
* Message Passing
InterProcess Communication (IPC)
Sleep and Wakeup
• Both Peterson and TSL have defect of requiring “busy waiting“
– Waste CPU time
– Priority inversion
InterProcess Communication (IPC)
Sleep and Wakeup
• Both Peterson and TSL have defect of requiring “busy waiting“
– Waste CPU time
CPU Critical Regions
– Priority inversion Priority: 5

B
InterProcess Communication (IPC)
Sleep and Wakeup
• Both Peterson and TSL have defect of requiring “busy waiting“
– Waste CPU time
CPU Critical Regions
– Priority inversion Priority: 5

A B

New  Ready, Priority: 2


InterProcess Communication (IPC)
Sleep and Wakeup
• Both Peterson and TSL have defect of requiring “busy waiting“
– Waste CPU time
CPU Critical Regions
– Priority inversion Priority: 5
Time-out

A B

New  Ready, Priority: 2


InterProcess Communication (IPC)
Sleep and Wakeup
• Both Peterson and TSL have defect of requiring “busy waiting“
– Waste CPU time
CPU Critical Regions
– Priority inversion Priority: 5

A B

New  Ready, Priority: 2


InterProcess Communication (IPC)
Sleep and Wakeup
• Both Peterson and TSL have defect of requiring “busy waiting“
– Waste CPU time
CPU Critical Regions
– Priority inversion Priority: 5
• Violate 4th rule Time-out

A B

New  Ready, Priority: 2


InterProcess Communication (IPC)
Sleep and Wakeup
• Both Peterson and TSL have defect of requiring “busy waiting“
– Waste CPU time
CPU Critical Regions
– Priority inversion Priority: 5
• Violate 4th rule Time-out

A B

New  Ready, Priority: 2

• Solution: the pair sleep and wakeup is used to direct blocking


instead of wasting CPU time when the processes are not allowed to
enter their critical regions
– Sleep is a system call that causes the caller to block, that is, be suspended
until the another process wakes it up
– Wakeup call has one parameter, the process to be awakened (ready)
– Alternatively, both sleep and wakeup each have one parameter, a memory
address used to match up sleeps and wakeups
InterProcess Communication (IPC)
Producer-Consumer Problem
Producer

Consumer
InterProcess Communication (IPC)
Producer-Consumer Problem
Producer

Wakeup Consumer
InterProcess Communication (IPC)
Producer-Consumer Problem
Producer

Consumer
InterProcess Communication (IPC)
Producer-Consumer Problem
Producer

Consumer
InterProcess Communication (IPC)
Producer-Consumer Problem
Producer

Consumer
InterProcess Communication (IPC)
Producer-Consumer Problem
Producer

Consumer
InterProcess Communication (IPC)
Producer-Consumer Problem
Producer

Consumer
InterProcess Communication (IPC)
Producer-Consumer Problem
Producer

Consumer
InterProcess Communication (IPC)
Producer-Consumer Problem
Producer

Consumer
InterProcess Communication (IPC)
Producer-Consumer Problem
Producer
Sleep

Consumer
InterProcess Communication (IPC)
Producer-Consumer Problem
Producer

Consumer
InterProcess Communication (IPC)
Producer-Consumer Problem
Producer
Wakeup

Consumer
InterProcess Communication (IPC)
Producer-Consumer Problem
Producer

Consumer

Sleep
InterProcess Communication (IPC)
Producer-Consumer Problem
Producer

Consumer

• Is known as the bounded-buffer problem


– Two processes share comment, fixed-size buffer
– The producer puts information into the buffer
– The consumer takes it out
• Sleeping conditions
– For producer, buffer full
– For consumer, buffer empty
• Wakeup conditions
– For producer, there is space in buffer
– For consumer, there are messages in buffer
InterProcess Communication (IPC)
Producer-Consumer Problem (cont)
• There are two
problems:
– Uncontrolled
concurrent
access to
variable count
– Wakeup
signalization
can be lost

Tanenbaum, Fig. 2-27.


InterProcess Communication (IPC)
Producer-Consumer Problem (cont)
• Above functions are executed incorrectly at the statements
“count = count + 1” of producer and “count = count – 1” of
consumer if the functions run concurrently
– Suppose that the value of the variable counter is 5.
– Then the value of the variable of counter may be 4, 5, or 6!!
• Two statements may be implemented in a machine language
as
InterProcess Communication (IPC)
Producer-Consumer Problem (cont)

• The first problem:


– Uncontrolled concurrent access to variable count
• The second problem
– Wakeup signalization can be lost
– Problems
• The buffer is empty and the consumer has just read count = 0  consumer sleep,
producer wakeup and insert data
– Count =1, consumer is sleeping, thus the producer calls wakeup consumer
– Consumer is not yet logically asleep, so the wakeup signal is lost
InterProcess Communication (IPC)
Semaphores
• (E.W.Dijkstra, 1965):
– A new variable type (semaphore) could have
• The value 0: no wakeups were saved
• The positive value: one or more wakeups were pending
– Two operations
• down (sleep)
– Checking the semaphore value is greater than 0
– If so, it decrements its value & continues, otherwise blocks the current process
– checking the value, change it, and possibly going to sleep, are all done as
single, indivisible atomic action
– Once a semaphore operation has started, no other process can access the
semaphore until the operation has completed or blocked
• up (wakeup)
– increments the semaphore’s value and wakes up a sleeping process (indivisible)
– no process ever blocks doing an up, just as no process ever blocks doing a
wakeup in the earlier model
• Semaphores solve the lost-wakeup problem
09/17/2023 Module A - Introduction 68/40
09/17/2023 Module A - Introduction 69/40
InterProcess Communication (IPC)
Solving Producer-Consumer Problem
• Uses 3 semaphores
– full: counting the
full slots (0)
– empty: counting the
empty slots (n slots)
– mutex: make sure
the producer and
consumer do not
access the buffer (1)
InterProcess Communication (IPC)
Solving Producer-Consumer Problem
• There are two ways of using semaphores:
– Mutual exclusion–binary semaphores(on 2 processes)
• Only one process can enters its critical region (reading or
writing the buffer) at the same time
– Synchronization – Condition checking
• Ensure the producer stops running when the buffer full
and the consumer stops running when it is empty
• That leads to complicated and tricky solutions
that can generate deadlocks
– Two downs were reversed in order in the producer
– So, mutex was decremented before empty
– If buffer is full, mutex equals 0 before empty decrease
→ producer is blocked
– In next time, the consumer tried to access the buffer, it
would do down on mutex to 0 → consumer is also
blocked, too
→ both producer and consumer are blocked forever
→ be careful to use semaphores
InterProcess Communication (IPC)
Mutexes
• Good for managing mutual exclusion to some shared resource or
piece of code (it is easy and efficient to implement using thread in
user mode)
• A mutex is a variable that can be in one of two states
– unlocked (0): the calling threads is free to enter the critical region
– locked (1): the calling thread is blocked until the thread in the critical region
is finished (busy)
• Two procedures are used
– mutex_lock: is called when a thread needs access to a critical region
– mutex_unlock: is called when a thread in the critical region is finished

Tanenbaum, Fig. 2-29.


InterProcess Communication (IPC)
Monitors
• Is a proposal of Brinch Hansen (1973) and Hoare (1974)
• Is a collection of procedures, variables, and data structures that are
all grouped together in a special kind of module or package
• Processes may call the procedures in a monitor whenever they want
to, but they cannot directly access monitor‘s internal data structures
from procedures declared outside the monitor (encapsulation)
• Only one process can be active in a monitor at any moment (mutual
exclusion)
• Monitor are programming language constructs
• When a process calls a monitor procedure, it must check to see if
any other procedure in currently active within monitor
– If so, the calling process is suspended until the other leaves.
– Otherwise, it enters the monitor
• Monitor are implemented using
– Mutual exclusion in monitor is ensured by the compiler
– Condition variables: provide the possibility of waiting
InterProcess Communication (IPC)
Condition Variables
• Used to wait for a specific condition to be fulfilled
• Two operations
– wait(): current process sleep, waiting (block state)
– signal(): a sleeping process is awaked
• When a process call wait, the other processes get access
into the monitor
• The wait must come before the signal and keep track the
state of each process with variables to ensure the signal
losing
InterProcess Communication (IPC)
Monitor functions
InterProcess Communication (IPC)
Solving Producer-Consumer Problem

Tanenbaum, Fig. 2-34.


InterProcess Communication (IPC)
Message Passing
• Using system calls (like semaphore) with 2
primitives
– send (destination, &message): sends a message
to given destination
– receive (source, &message): receives a message
from a given resource. If no message is
available, the receiver can block until one
arrives
• Message-Passing System is used for the
communicating processes are on different
machines connected by a network
– To guard against lost messages, sender and
receiver can agree that as soon as a message has
been received, the receiver will send back a
special acknowledgement message (ensuring
both process are blocked forever)
InterProcess Communication (IPC)
Solving Producer-Consumer Problem

Tanenbaum, Fig. 2-36.


InterProcess Communication (IPC)
Barriers
• Is intended for groups of processes rather than two process
producer-consumer type situations
• The applications are divided into phases and have the rule that no
process may proceed into the next phase until all processes are
ready to proceed to the next phase.
• This behavior may be archived by placing a barrier at the end of
each phase. When a process reaches the barrier, it is blocked
until all processes have reached the barrier.

Tanenbaum, Fig. 2-37.


Summary
• InterProcess Communication

Q&A
Next Lecture
• Scheduling
• Scheduling Criteria/ Properties
• Scheduling decisions are applied to determine which
processes are executed (algorithms or mechanism)
• Scheduling on Processes and Threads

You might also like