Recall: Multithreaded Stack Example
• Consider the following code blocks:
proc A() {
proc B() {
Copyright By PowCoder代写 加微信 powcoder
while(TRUE) {
yield(); }
• Suppose we have 2 threads:
– Threads S and T
run_new_thread
run_new_thread
Thread S’s switch returns to Thread T’s (and vice versa)
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Stack growth
Recall: Use of Timer Interrupt to Return Control
• Solution to our dispatcher problem
– Use the timer interrupt to force scheduling decisions
Some Routine
TimerInterrupt
run_new_thread
• Timer Interrupt routine:
TimerInterrupt() {
DoPeriodicHouseKeeping();
run_new_thread();
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Stack growth
Hardware context switch support in x86
• Syscall/Intr (U 🡨 K)
– PL 3 🡨 0;
– TSS 🡨 EFLAGS, CS:EIP;
– SS:ESP 🡨 k-thread stack (TSS PL 0);
– push (old) SS:ESP onto (new) k-stack
– push (old) eflags, cs:eip,
– CS:EIP 🡨
– Handler saves other regs, etc
– Does all its works, possibly choosing other threads, changing PTBR (CR3)
– kernel thread has set up user GPRs
• iret (K🡨U)
– PL 0 🡨 3;
– Eflags, CS:EIP 🡨 popped off k-stack
– SS:ESP 🡨 popped off k-stack
pg 2,942 of 4,922 of x86 reference manual
Pintos: tss.c, intr-stubs.S
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Pintos: Kernel Crossing on Syscall or Interrupt
user stack
Joseph & Kubiatowicz CS162 © UCB Spring 2022
kernel code
kernel thread stack
syscall / interrupt
processing ready to resume
Pintos: Context Switch – Scheduling
user stack
user’ stack
kernel code
kernel thread stack
switch kernel threads
Pintos: switch.S
Joseph & Kubiatowicz CS162 © UCB Spring 2022
syscall / interrupt
processing ready to resume
MT Kernel 1T Process ala Pintos/x86
magic # list
priority stack status
magic # list
priority stack status
User stack
User stack
Each user process/thread associated with a kernel thread, described by a 4KB page object containing TCB and kernel stack for the kernel thread
Joseph & Kubiatowicz CS162 © UCB Spring 2022
In User thread, w/ Kernel thread waiting
magic # list
priority stack status
magic # list
priority stack status
User stack
User stack
Joseph & Kubiatowicz CS162 © UCB Spring 2022
• x86 CPU holds interrupt SP in register
• During user thread execution, associated kernel thread is “standing by”
In Kernel Thread: No User Component
magic # list
priority stack status
User stack
User stack
Joseph & Kubiatowicz CS162 © UCB Spring 2022
• Kernel threads execute with small stack in thread structure
• Pure kernel threads have no corresponding user-mode thread
User → Kernel (exceptions, syscalls)
magic # list
priority stack status
User stack
User stack
Joseph & Kubiatowicz CS162 © UCB Spring 2022
• Mechanism to resume k-thread goes through interrupt vector
Kernel → User
magic # list
priority stack status
magic # list
priority stack status
User stack
User stack
Joseph & Kubiatowicz CS162 © UCB Spring 2022
• Interrupt return (iret) restores user stack, IP, and PL
Pintos Interrupt Processing
intrNN_stub()
push 0x20 (int #)
jmp intr_entry
Wrapper for generic handler
intr_entry:
save regs as frame
set up kernel env.
call intr_handler
intr_exit:
restore regs
push 0x21 (int #)
jmp intr_entry
Hardware interrupt vector
Joseph & Kubiatowicz CS162 © UCB Spring 2022
User → Kernel via interrupt vector
magic # list
priority stack status
User stack
User stack
255 intr vector
• Interrupt transfers control through the Interrupt Vector (IDT in x86)
• iret restores user stack and priority level (PL)
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Switch to Kernel Thread for Process
magic # list
priority stack status
User stack
User stack
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Pintos Interrupt Processing
interrupt.c
Intr_handler(*frame)
– classify
– dispatch
– maybe thread yield
intrNN_stub()
push 0x20 (int #)
jmp intr_entry
Wrapper for generic handler
intr_entry:
save regs as frame
set up kernel env.
call intr_handler
intr_exit:
restore regs
push 0x21 (int #)
jmp intr_entry
timer_intr(*frame)
thread_tick()
Hardware interrupt vector
Pintos intr_handlers
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Timer may trigger thread switch
• thread_tick
– Updates thread counters
– If quanta exhausted, sets yield flag
• thread_yield
– On path to rtn from interrupt
– Sets current thread back to READY
– Pushes it back on ready_list
– Calls schedule to select next thread to run upon iret
• Schedule
Selects next thread to run
Calls switch_threads to change regs to point to stack for thread to resume
Sets its status to RUNNING
If user thread, activates the process Returns back to intr_handler
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Thread Switch (switch.S)
magic # list
priority stack status
User stack
User stack
Joseph & Kubiatowicz CS162 © UCB Spring 2022
• switch_threads: save regs on current small stack, change SP,
return from destination threads call to switch_threads
Pintos Return from Processing
interrupt.c
Intr_handler(*frame)
– classify
– dispatch
– maybe thread yield
intrNN_stub()
push 0x20 (int #)
jmp intr_entry
Wrapper for generic handler
intr_entry:
save regs as frame
set up kernel env.
call intr_handler
intr_exit:
restore regs
push 0x20 (int #)
jmp intr_entry
255 Hardware
interrupt vector
Resume Some Thread
timer_intr(*frame)
thread_tick()
thread_yield()
– schedule
Pintos intr_handlers
schedule()
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Different User Thread
magic # list
priority stack status
magic # list
priority stack status
User stack
User stack
• iret restores user stack and priority level (PL)
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Famous Quote WRT Scheduling:
, Unix V6, slp.c:
“If the new process paused because it was swapped out, set the stack level to the last call to savu(u_ssav).This means that the return which is executed immediately after the call to aretu actually returns from the last routine which did the savu.”
“You are not expected to understand this.”
Source: , Unix V6 slp.c (context-switching code) as per The
Unix Heritage Society(tuhs.org); gif by . Included by . Butt in CS3204 from
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Goals for Rest of Today
• Challenges and Pitfalls of Concurrency
• Synchronization Operations/Critical Sections • How to build a lock?
• Atomic Instructions
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Recall: Multiprocessing vs Multiprogramming
• Some Definitions:
– Multiprocessing ≡ Multiple CPUs
– Multiprogramming ≡ Multiple Jobs or Processes – Multithreading ≡ Multiple threads per Process
• What does it mean to run two threads “concurrently”?
– Scheduler is free to run threads in any order and interleaving: FIFO, Random, …
– Dispatcher can choose to run each thread to completion or time-slice in big chunks or small chunks
Multiprocessing
Multiprogramming
A B C A B C B
Joseph & Kubiatowicz CS162 © UCB Spring 2022
ATM Bank Server
• ATM server problem:
– Service a set of requests
– Do so without corrupting database – Don’t hand out too much money
Joseph & Kubiatowicz CS162 © UCB Spring 2022
ATM bank server example
• Suppose we wanted to implement a server process to handle requests from an ATM network:
BankServer() {
while (TRUE) {
ReceiveRequest(&op, &acctId, &amount);
ProcessRequest(op, acctId, amount);
ProcessRequest(op, acctId, amount) {
if (op == deposit) Deposit(acctId, amount);
else if …
Deposit(acctId, amount) {
acct = GetAccount(acctId); /* may use disk I/O */
acct->balance += amount;
StoreAccount(acct); /* Involves disk I/O */
• How could we speed this up?
– More than one request being processed at once
– Event driven (overlap computation and I/O)
– Multiple threads (multi-proc, or overlap comp and I/O)
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Event Driven Version of ATM server
• Suppose we only had one CPU
– Still like to overlap I/O with computation
– Without threads, we would have to rewrite in event-driven style
BankServer() {
while(TRUE) {
event = WaitForNextEvent();
if (event == ATMRequest)
StartOnRequest();
else if (event == AcctAvail)
ContinueRequest();
else if (event == AcctStored)
FinishRequest();
– This technique is used for graphical programming
• Complication:
– What if we missed a blocking I/O step?
– What if we have to split code into hundreds of pieces which could be blocking?
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Can Threads Make This Easier?
• Threads yield overlapped I/O and computation without “deconstructing” code into non-blocking fragments
– One thread per request
• Requests proceeds to completion, blocking as required:
Deposit(acctId, amount) {
acct = GetAccount(actId);/* May use disk I/O */ acct->balance += amount;
StoreAccount(acct); /* Involves disk I/O */
• Unfortunately, shared state can get corrupted:
Thread 1 Thread 2
load r1, acct->balance
load r1, acct->balance
add r1, amount2
store r1, acct->balance
add r1, amount1
store r1, acct->balance
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Recall: Possible Executions
2/8/22 Joseph & Kubiatowicz CS162 © UCB Spring 2022 Lec 7.26
Problem is at the Lowest Level
• Most of the time, threads are working on separate data, so scheduling doesn’t matter:
Thread A Thread B
x = 1; y = 2;
• However, what about (Initially, y = 12):
Thread A Thread B
x = 1; y = 2;
x = y+1; y = y*2;
– What are the possible values of x?
• Or, what are the possible values of x below?
Thread A Thread B
x = 1; x = 2;
– X could be 1 or 2 (non-deterministic!)
– Could even be 3 for serial processors:
» Thread A writes 0001, B writes 0010 → scheduling order ABABABBA yields 3!
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Atomic Operations
• To understand a concurrent program, we need to know what the underlying indivisible operations are!
• Atomic Operation: an operation that always runs to completion or not at all
– It is indivisible: it cannot be stopped in the middle and state cannot be modified by
someone else in the middle
– Fundamental building block – if no atomic operations, then have no way for threads to work together
• On most machines, memory references and assignments (i.e. loads and stores) of words are atomic
– Consequently – weird example that produces “3” on previous slide can’t happen
• Many instructions are not atomic
– Double-precision floating point store often not atomic
– VAX and IBM 360 had an instruction to copy a whole array
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Another Concurrent Program Example
Two threads, A and B, compete with each other – One tries to increment a shared counter
– The other tries to decrement the counter
Assume that memory loads and stores are atomic, but incrementing and decrementing are not atomic
Who wins? Could be either
Is it guaranteed that someone wins? Why or why not?
What if both threads have their own CPU running at same speed? Is it guaranteed that it goes on forever?
i = 0; i = 0; while (i < 10)
while (i > -10)
i = i – 1;
i = i + 1;
printf(“A wins!”); printf(“B wins!”);
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Hand Simulation Multiprocessor Example
• Inner loop looks like this:
Thread A Thread B
r1=0 load r1, M[i]
r1=0 load r1, M[i]
r1=1 add r1, r1, 1
r1=-1 sub r1, r1, 1
M[i]=1store r1, M[i]
M[i]=-1 store r1, M[i]
• Hand Simulation:
– And we’re off. A gets off to an early start
– B says “hmph, better go fast” and tries really hard
– A goes ahead and writes “1”
– B goes and writes “-1”
– A says “HUH??? I could have sworn I put a 1 there”
• Could this happen on a uniprocessor? With Hyperthreads?
– Yes! Unlikely, but if you are depending on it not happening, it will and your system will break…
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Definitions
• Synchronization: using atomic operations to ensure cooperation between threads
– For now, only loads and stores are atomic
– We are going to show that its hard to build anything useful with only reads and writes
• Mutual Exclusion: ensuring that only one thread does a particular thing at a time
– One thread excludes the other while doing its task
• Critical Section: piece of code that only one thread can execute at once. Only one thread at a time will get into this section of code
– Critical section is the result of mutual exclusion
– Critical section and mutual exclusion are two ways of describing the same thing
Joseph & Kubiatowicz CS162 © UCB Spring 2022
• Lock: prevents someone from doing something
– Lock() before entering critical section and before accessing
shared data
– Unlock() when leaving, after accessing shared data
– Wait if locked
» Important idea: all synchronization involves waiting
• Locks need to be allocated and initialized:
– structure Lock mylock or pthread_mutex_t mylock;
– lock_init(&mylock) or mylock = PTHREAD_MUTEX_INITIALIZER;
• Locks provide two atomic operations:
– acquire(&mylock) – wait until lock is free; then mark it as busy » After this returns, we say the calling thread holds the lock
– release(&mylock) – mark lock as free
» Should only be called by a thread that currently holds the lock » After this returns, the calling thread no longer holds the lock
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Fix banking problem with Locks!
• Identify critical sections (atomic instruction sequences) and add locking:
Deposit(acctId, amount) {
acquire(&mylock)
acct = GetAccount(actId);
acct->balance += amount;
StoreAccount(acct);
// Wait if someone else in critical
Critical Section
// Release someone into critical section
release(&mylock)
Critical Section
acquire(&mylock)
Threads serialized by lock through critical section. Only one thread at a time
CA release(&mylock)
• Must use SAME lock (mylock) with all of the methods (Withdraw, etc…) – Shared with all threads!Joseph & Kubiatowicz CS162 © UCB Spring 2022
Correctness Requirements
• Threaded programs must work for all interleavings of thread instruction sequences
– Cooperating threads inherently non-deterministic and non-reproducible
– Really hard to debug unless carefully designed! • Example:Therac-25
– Machine for radiation therapy
» Software control of electron accelerator and electron beam/ Xray production
» Software control of dosage
– Software errors caused the death of several patients
» A series of race conditions on shared variables and poor software design
» “They determined that data entry speed during editing was the key factor in producing the error condition: If the prescription data was edited at a fast pace, the overdose occurred.”
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Motivating Example:“Too Much Milk”
• Great thing about OS’s – analogy between problems in OS and problems in real life
– Help you understand real life problems better – But, computers are much stupider than people
• Example: People need to coordinate:
Look in Fridge. Out of milk
Leave for store
Arrive at store
Look in Fridge. Out of milk
Leave for store
Arrive home, put milk away
Arrive at store
Arrive home, put milk away
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Solve with a lock?
• Recall: Lock prevents someone from doing something – Lock before entering critical section
– Unlock when leaving
– Wait if locked
» Important idea: all synchronization involves waiting
• For example: fix the milk problem by putting a key on the refrigerator – Lock it and take key if you are going to go buy milk
– Fixes too much: roommate angry if only wants OJ
• Of Course – We don’t know how to make a lock yet – Let’s see if we can answer this question!
Joseph & Kubiatowicz CS162 © UCB Spring 2022
Too Much Milk: Correctness Properties
• Need to be careful about correctness of concurrent programs, since non-deterministic
– Impulse is to start coding first, then when it doesn’t work, pull hair out – Instead, think first, then code
– Always write down behavior first
• What are the correctness properties for the “Too much milk” problem??? – Never more than one person buys
– Someone buys if needed
• First attempt: Restrict ourselves to
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com