SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Reminder: Project Ideas are
due by 11:59pm tonight!
Plan for Today
Recap: Dijkstra’s Mutual Exclusion Problem
Why Obvious Solutions Fail
Practical Solutions with Modern Processors
Dijkstra’s Solution
Lamport’s Solution
1
Reminder: Project Ideas are
due by 11:59pm tonight!
2
3
Final Keynote (Sunday):
Steve Huffman
4
5
Decoy Project!
6
Lessons for your Project Submissions:
1. Don’t submit something I will think is a
decoy project! (Too late for that here)
2. Don’t do something that involves breaking
into my house.
3. Do do something creative and unexpected.
7
T2 T3 T4T1
N independent threads
Shared Memory (atomic read and write)
T5 Program:
loop {
non-critical {
…
}
critical {
…
}
}
Requirements:
1. Only one thread may be in the critical section at any time.
2. Each must eventually be able to enter its critical section.
3. Must be symmetrical (all run same program).
4. Cannot make any assumptions about speed of threads.
Clever “Cheating” Solution
8
loop {
if turn == i:
critical_section;
turn = i + 1;
}
T2 T3T1
Shared Memory
turn:
Initially, turn = 1
9
loop {
if turn == i:
critical_section;
turn = i + 1;
}
Initially, turn = 1
Attempted Solution
10
loop {
if not lock:
lock = true;
critical_section;
lock = false;
}
T2 T3T1
Shared Memory
lock:
Attempted Fix
11
loop {
if lock == 0:
lock = i;
if lock == i:
critical_section;
lock = 0;
}
T2 T3T1
Shared Memory
lock:
Attempted Fix of Fix
12
loop {
if lock1 == 0:
lock1 = i;
if lock1 == i:
if lock2 == 0:
lock2 = i;
if lock2 == i:
critical_section;
lock2 = 0;
lock1 = 0;
}
T2 T3T1
Shared Memory
lock1: lock2:
Attempted Fix of Fix of Fix …
13
loop {
if lock1 == 0:
lock1 = i;
if lock1 == i:
if lock2 == 0:
lock2 = i;
if lock2 == i:
critical_section;
lock2 = 0;
lock1 = 0;
}
T2 T3T1
Shared Memory
lock1: lock2:
Do we need to see why 3-locks still breaks?
Uniprocessor
Easy (Kernel Cheating) Solution
14
loop {
non-critical;
disable interrupts
critical_section;
enable interrupts
}
T2 T3T1
Shared Memory
15
ironkernel: arch/arm/cpu/interrupt.rs
16
ironkernel: arch/arm/cpu/interrupt.rs
CPSR: Current Program Status Register
Uniprocessor
Easy (Kernel Cheating) Solution
17
loop {
non-critical;
disable interrupts
critical_section;
enable interrupts
}
T2 T3T1
Shared Memory
How well does this solution work for modern kernels?
Easy (Cheating) Solution
18
T2 T3T1
Shared Memory
(with atomic
read/write/test&set)
lock:
test_and_set(v)
returns current value of v
sets value of v to true
Easy (Cheating) Solution
19
loop {
if not test_and_set(lock):
critical_section;
lock = false;
}
T2 T3T1
Shared Memory
(with atomic
read/write/test&set)
lock:
test_and_set(v)
returns current value of v
sets value of v to true
Does your processor provide such
an instruction?
20
21
Intel x86
22
ARMv7
23
Implementing a Mutex Lock
24
lock_mutex(lock);
critical
unlock_mutex(lock);
LDREX <dest> <location>
<dest> = <location>
Sets monitor on <location> in Exclusive state
STREX <success> <value> <location>
Conditionally store <value> into exclusive <location>.
If permitted, <success> = 1 and <location> = <value>.
If not, <success> = 0 and <location> value unchanged.
Context switch clears monitor (Open) state.
25
lock_mutex(lock);
critical
unlock_mutex(lock);
lock_mutex(lock):
try_again:
LDREX R2, [lock]
if R2 goto try_again
STREX R2, 1, [lock]
if not R2 goto try_again
unlock_mutex(lock):
STR [lock], 0
LDREX <dest> <location>
<dest> = <location>
Sets monitor on <location> in Exclusive state
STREX <success> <value> <location>
Conditionally store <value> into exclusive <location>.
If permitted, <success> = 1 and <location> = <value>.
If not, <success> = 0 and <location> value unchanged.
26
lock_mutex(lock);
critical
unlock_mutex(lock);
lock_mutex(lock):
try_again:
LDREX R2, [lock]
if R2 goto try_again
STREX R2, 1, [lock]
if not R2 goto try_again
unlock_mutex(lock):
STR [lock], 0
What if you care about energy?
27
28
WFE and WFI do not provide synchronization!
Just hints to the processor to save energy.
29
ARMv7
Why two instructions like this instead of one?
30
T2 T3 T4T1
Shared Memory (atomic read and write)
T5
Program:
loop {
non-critical {
…
}
critical {
…
}
}
Requirements:
1. Only one thread may be in the critical section at any time.
2. Each must eventually be able to enter its critical section.
3. Must be symmetrical (all run same program).
4. Cannot make any assumptions about speed of threads.
no special combined atomic operations (e.g., test-and-set, LDREX/STREX)
31
Dijkstra (1973)
From Edgar Daylight’s collection:
http://www.dijkstrascry.com/node/59
1965
32
33
Program for Processor i
loop {
b[i] := false
L1: if k != i
c[i] := true
if b[k]
k := i
goto L1
else:
c[i] := false
for j in [1, …, N]:
if j != i and not c[j]:
goto L1
critical section;
c[i] := true
b[i] := true
}
Initialization
b[1:N] = [true, true, …]
c[1:N] = [true, true, …]
k = choose([1..N])
34
Safety: only one program can be
in critical section
Program for Processor i
loop {
b[i] := false
L1: if k != i
c[i] := true
if b[k]:
k := i
goto L1
else:
c[i] := false
for j in [1, …, N]:
if j != i and not c[j]:
goto L1
critical section;
c[i] := true
b[i] := true
}
35
Program for Processor i
loop {
b[i] := false
L1: if k != i
c[i] := true
if b[k]:
k := i
goto L1
else:
c[i] := false;
L4: for j in [1, …, N]:
if j != i and not c[j]:
goto L1
critical section;
c[i] := true
b[i] := true
}
How do we know none of the c[.]’s
changed during the loop?
Charge
Think about Dijkstra’s Solution:
How does it guarantee mutual exclusion?
How does it guarantee liveness?
Submit Project Idea by 11:59pm Tonight
36

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Flash! (Modern File Systems)
Flash! (Modern File Systems)Flash! (Modern File Systems)
Flash! (Modern File Systems)
 
The Internet
The InternetThe Internet
The Internet
 
Nicpaper2009
Nicpaper2009Nicpaper2009
Nicpaper2009
 
Zero to a Billion in 4.86 Years (A Whirlwind History of Operating Systems)
Zero to a Billion in 4.86 Years (A Whirlwind History of Operating Systems)Zero to a Billion in 4.86 Years (A Whirlwind History of Operating Systems)
Zero to a Billion in 4.86 Years (A Whirlwind History of Operating Systems)
 
Scheduling in Linux and Web Servers
Scheduling in Linux and Web ServersScheduling in Linux and Web Servers
Scheduling in Linux and Web Servers
 
Gash Has No Privileges
Gash Has No PrivilegesGash Has No Privileges
Gash Has No Privileges
 
Kernel Recipes 2019 - Formal modeling made easy
Kernel Recipes 2019 - Formal modeling made easyKernel Recipes 2019 - Formal modeling made easy
Kernel Recipes 2019 - Formal modeling made easy
 
java memory management & gc
java memory management & gcjava memory management & gc
java memory management & gc
 
Lowering STM Overhead with Static Analysis
Lowering STM Overhead with Static AnalysisLowering STM Overhead with Static Analysis
Lowering STM Overhead with Static Analysis
 
Storage
StorageStorage
Storage
 
Implementing STM in Java
Implementing STM in JavaImplementing STM in Java
Implementing STM in Java
 
Kernel Recipes 2019 - RCU in 2019 - Joel Fernandes
Kernel Recipes 2019 - RCU in 2019 - Joel FernandesKernel Recipes 2019 - RCU in 2019 - Joel Fernandes
Kernel Recipes 2019 - RCU in 2019 - Joel Fernandes
 
Parallel program design
Parallel program designParallel program design
Parallel program design
 
Kernel Recipes 2019 - CVEs are dead, long live the CVE!
Kernel Recipes 2019 - CVEs are dead, long live the CVE!Kernel Recipes 2019 - CVEs are dead, long live the CVE!
Kernel Recipes 2019 - CVEs are dead, long live the CVE!
 
Where destructors meet threads
Where destructors meet threadsWhere destructors meet threads
Where destructors meet threads
 
john-devkit: 100 типов хешей спустя / john-devkit: 100 Hash Types Later
john-devkit: 100 типов хешей спустя / john-devkit: 100 Hash Types Laterjohn-devkit: 100 типов хешей спустя / john-devkit: 100 Hash Types Later
john-devkit: 100 типов хешей спустя / john-devkit: 100 Hash Types Later
 
Java Memory Model
Java Memory ModelJava Memory Model
Java Memory Model
 
grsecurity and PaX
grsecurity and PaXgrsecurity and PaX
grsecurity and PaX
 
Exploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernelExploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernel
 
Crafting a Ready-to-Go STM
Crafting  a Ready-to-Go STMCrafting  a Ready-to-Go STM
Crafting a Ready-to-Go STM
 

Andere mochten auch

Mutual Exclusion in Wireless Sensor and Actor Networks
Mutual Exclusion in Wireless Sensor and Actor NetworksMutual Exclusion in Wireless Sensor and Actor Networks
Mutual Exclusion in Wireless Sensor and Actor Networks
Zhenyun Zhuang
 
dos mutual exclusion algos
dos mutual exclusion algosdos mutual exclusion algos
dos mutual exclusion algos
Akhil Sharma
 
Mutual Exclusion using Peterson's Algorithm
Mutual Exclusion using Peterson's AlgorithmMutual Exclusion using Peterson's Algorithm
Mutual Exclusion using Peterson's Algorithm
Souvik Roy
 
Mutual Exclusion Election (Distributed computing)
Mutual Exclusion Election (Distributed computing)Mutual Exclusion Election (Distributed computing)
Mutual Exclusion Election (Distributed computing)
Sri Prasanna
 

Andere mochten auch (17)

Pbcbt an improvement of ntbcbt algorithm
Pbcbt an improvement of ntbcbt algorithmPbcbt an improvement of ntbcbt algorithm
Pbcbt an improvement of ntbcbt algorithm
 
Mutual Exclusion in Wireless Sensor and Actor Networks
Mutual Exclusion in Wireless Sensor and Actor NetworksMutual Exclusion in Wireless Sensor and Actor Networks
Mutual Exclusion in Wireless Sensor and Actor Networks
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Chapter05 new
Chapter05 newChapter05 new
Chapter05 new
 
A New Function-based Framework for Classification and Evaluation of Mutual Ex...
A New Function-based Framework for Classification and Evaluation of Mutual Ex...A New Function-based Framework for Classification and Evaluation of Mutual Ex...
A New Function-based Framework for Classification and Evaluation of Mutual Ex...
 
Mutual exclusion and synchronization
Mutual exclusion and synchronizationMutual exclusion and synchronization
Mutual exclusion and synchronization
 
Multiprocessors(performance and synchronization issues)
Multiprocessors(performance and synchronization issues)Multiprocessors(performance and synchronization issues)
Multiprocessors(performance and synchronization issues)
 
Inter process communication
Inter process communicationInter process communication
Inter process communication
 
dos mutual exclusion algos
dos mutual exclusion algosdos mutual exclusion algos
dos mutual exclusion algos
 
Mutual Exclusion using Peterson's Algorithm
Mutual Exclusion using Peterson's AlgorithmMutual Exclusion using Peterson's Algorithm
Mutual Exclusion using Peterson's Algorithm
 
Mutual exclusion
Mutual exclusionMutual exclusion
Mutual exclusion
 
Lamport’s algorithm for mutual exclusion
Lamport’s algorithm for mutual exclusionLamport’s algorithm for mutual exclusion
Lamport’s algorithm for mutual exclusion
 
Semaphores OS Basics
Semaphores OS BasicsSemaphores OS Basics
Semaphores OS Basics
 
Mutual Exclusion Election (Distributed computing)
Mutual Exclusion Election (Distributed computing)Mutual Exclusion Election (Distributed computing)
Mutual Exclusion Election (Distributed computing)
 
Semaphores
SemaphoresSemaphores
Semaphores
 
OS Process Synchronization, semaphore and Monitors
OS Process Synchronization, semaphore and MonitorsOS Process Synchronization, semaphore and Monitors
OS Process Synchronization, semaphore and Monitors
 
8. mutual exclusion in Distributed Operating Systems
8. mutual exclusion in Distributed Operating Systems8. mutual exclusion in Distributed Operating Systems
8. mutual exclusion in Distributed Operating Systems
 

Ähnlich wie Mutual Exclusion

Fast dynamic analysis, Kostya Serebryany
Fast dynamic analysis, Kostya SerebryanyFast dynamic analysis, Kostya Serebryany
Fast dynamic analysis, Kostya Serebryany
yaevents
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded Programming
Adil Jafri
 

Ähnlich wie Mutual Exclusion (20)

How I Sped up Complex Matrix-Vector Multiplication: Finding Intel MKL's "S
How I Sped up Complex Matrix-Vector Multiplication: Finding Intel MKL's "SHow I Sped up Complex Matrix-Vector Multiplication: Finding Intel MKL's "S
How I Sped up Complex Matrix-Vector Multiplication: Finding Intel MKL's "S
 
Memory model
Memory modelMemory model
Memory model
 
Optimizing Parallel Reduction in CUDA : NOTES
Optimizing Parallel Reduction in CUDA : NOTESOptimizing Parallel Reduction in CUDA : NOTES
Optimizing Parallel Reduction in CUDA : NOTES
 
Fast dynamic analysis, Kostya Serebryany
Fast dynamic analysis, Kostya SerebryanyFast dynamic analysis, Kostya Serebryany
Fast dynamic analysis, Kostya Serebryany
 
Константин Серебряный "Быстрый динамичекский анализ программ на примере поиск...
Константин Серебряный "Быстрый динамичекский анализ программ на примере поиск...Константин Серебряный "Быстрый динамичекский анализ программ на примере поиск...
Константин Серебряный "Быстрый динамичекский анализ программ на примере поиск...
 
Meltdown & spectre
Meltdown & spectreMeltdown & spectre
Meltdown & spectre
 
Meltdown & Spectre
Meltdown & Spectre Meltdown & Spectre
Meltdown & Spectre
 
Data race
Data raceData race
Data race
 
Lockless Programming GDC 09
Lockless Programming GDC 09Lockless Programming GDC 09
Lockless Programming GDC 09
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
 
Synchronization problem with threads
Synchronization problem with threadsSynchronization problem with threads
Synchronization problem with threads
 
TMPA-2017: Distributed Analysis of the BMC Kind: Making It Fit the Tornado Su...
TMPA-2017: Distributed Analysis of the BMC Kind: Making It Fit the Tornado Su...TMPA-2017: Distributed Analysis of the BMC Kind: Making It Fit the Tornado Su...
TMPA-2017: Distributed Analysis of the BMC Kind: Making It Fit the Tornado Su...
 
cs2110Concurrency1.ppt
cs2110Concurrency1.pptcs2110Concurrency1.ppt
cs2110Concurrency1.ppt
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded Programming
 
Killer Bugs From Outer Space
Killer Bugs From Outer SpaceKiller Bugs From Outer Space
Killer Bugs From Outer Space
 
GPU-Accelerated Parallel Computing
GPU-Accelerated Parallel ComputingGPU-Accelerated Parallel Computing
GPU-Accelerated Parallel Computing
 
Untangling the Intricacies of Thread Synchronization in the PREEMPT_RT Linux ...
Untangling the Intricacies of Thread Synchronization in the PREEMPT_RT Linux ...Untangling the Intricacies of Thread Synchronization in the PREEMPT_RT Linux ...
Untangling the Intricacies of Thread Synchronization in the PREEMPT_RT Linux ...
 
L3-.pptx
L3-.pptxL3-.pptx
L3-.pptx
 
Lect04
Lect04Lect04
Lect04
 

Mehr von David Evans

Mehr von David Evans (20)

Cryptocurrency Jeopardy!
Cryptocurrency Jeopardy!Cryptocurrency Jeopardy!
Cryptocurrency Jeopardy!
 
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for Cypherpunks
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for CypherpunksTrick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for Cypherpunks
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for Cypherpunks
 
Hidden Services, Zero Knowledge
Hidden Services, Zero KnowledgeHidden Services, Zero Knowledge
Hidden Services, Zero Knowledge
 
Anonymity in Bitcoin
Anonymity in BitcoinAnonymity in Bitcoin
Anonymity in Bitcoin
 
Midterm Confirmations
Midterm ConfirmationsMidterm Confirmations
Midterm Confirmations
 
Scripting Transactions
Scripting TransactionsScripting Transactions
Scripting Transactions
 
How to Live in Paradise
How to Live in ParadiseHow to Live in Paradise
How to Live in Paradise
 
Bitcoin Script
Bitcoin ScriptBitcoin Script
Bitcoin Script
 
Mining Economics
Mining EconomicsMining Economics
Mining Economics
 
Mining
MiningMining
Mining
 
The Blockchain
The BlockchainThe Blockchain
The Blockchain
 
Becoming More Paranoid
Becoming More ParanoidBecoming More Paranoid
Becoming More Paranoid
 
Asymmetric Key Signatures
Asymmetric Key SignaturesAsymmetric Key Signatures
Asymmetric Key Signatures
 
Introduction to Cryptography
Introduction to CryptographyIntroduction to Cryptography
Introduction to Cryptography
 
Class 1: What is Money?
Class 1: What is Money?Class 1: What is Money?
Class 1: What is Money?
 
Multi-Party Computation for the Masses
Multi-Party Computation for the MassesMulti-Party Computation for the Masses
Multi-Party Computation for the Masses
 
Proof of Reserve
Proof of ReserveProof of Reserve
Proof of Reserve
 
Silk Road
Silk RoadSilk Road
Silk Road
 
Blooming Sidechains!
Blooming Sidechains!Blooming Sidechains!
Blooming Sidechains!
 
Useful Proofs of Work, Permacoin
Useful Proofs of Work, PermacoinUseful Proofs of Work, Permacoin
Useful Proofs of Work, Permacoin
 

Kürzlich hochgeladen

Kürzlich hochgeladen (18)

Life Lessons to Learn ~ A Free Full-Color eBook (English).pdf
Life Lessons to Learn ~ A Free Full-Color eBook (English).pdfLife Lessons to Learn ~ A Free Full-Color eBook (English).pdf
Life Lessons to Learn ~ A Free Full-Color eBook (English).pdf
 
Codex Singularity: Search for the Prisca Sapientia
Codex Singularity: Search for the Prisca SapientiaCodex Singularity: Search for the Prisca Sapientia
Codex Singularity: Search for the Prisca Sapientia
 
A373 true knowledge Not according to true knowledge, knowledge/true knowledg...
A373 true knowledge  Not according to true knowledge, knowledge/true knowledg...A373 true knowledge  Not according to true knowledge, knowledge/true knowledg...
A373 true knowledge Not according to true knowledge, knowledge/true knowledg...
 
RTPM - DSHS Class of 2024 - Baccalaureate Mass
RTPM - DSHS Class of 2024 - Baccalaureate MassRTPM - DSHS Class of 2024 - Baccalaureate Mass
RTPM - DSHS Class of 2024 - Baccalaureate Mass
 
Deerfoot Church of Christ Bulletin 5 26 24
Deerfoot Church of Christ Bulletin 5 26 24Deerfoot Church of Christ Bulletin 5 26 24
Deerfoot Church of Christ Bulletin 5 26 24
 
2024 Wisdom Touch Tour Houston Slide Deck
2024 Wisdom Touch Tour Houston Slide Deck2024 Wisdom Touch Tour Houston Slide Deck
2024 Wisdom Touch Tour Houston Slide Deck
 
The Prophecy of Enoch in Jude 14-16_.pptx
The Prophecy of Enoch in Jude 14-16_.pptxThe Prophecy of Enoch in Jude 14-16_.pptx
The Prophecy of Enoch in Jude 14-16_.pptx
 
The_Chronological_Life_of_Christ_Part_101_Misordered_Priorities
The_Chronological_Life_of_Christ_Part_101_Misordered_PrioritiesThe_Chronological_Life_of_Christ_Part_101_Misordered_Priorities
The_Chronological_Life_of_Christ_Part_101_Misordered_Priorities
 
Saint Vincent de Paul and Saint Louise de Marillac Played a Central Part in t...
Saint Vincent de Paul and Saint Louise de Marillac Played a Central Part in t...Saint Vincent de Paul and Saint Louise de Marillac Played a Central Part in t...
Saint Vincent de Paul and Saint Louise de Marillac Played a Central Part in t...
 
Reflections and Aspirations for Wesak 2024 (Eng. & Chi.).pptx
Reflections and Aspirations for Wesak  2024  (Eng. & Chi.).pptxReflections and Aspirations for Wesak  2024  (Eng. & Chi.).pptx
Reflections and Aspirations for Wesak 2024 (Eng. & Chi.).pptx
 
A Chronology of the Resurrection Appearances
A Chronology of the Resurrection AppearancesA Chronology of the Resurrection Appearances
A Chronology of the Resurrection Appearances
 
English - The Book of Leviticus the Third Book of Moses.pdf
English - The Book of Leviticus the Third Book of Moses.pdfEnglish - The Book of Leviticus the Third Book of Moses.pdf
English - The Book of Leviticus the Third Book of Moses.pdf
 
308 David Displeased the Lord 309 What Will it Take for God to Get Your Atten...
308 David Displeased the Lord 309 What Will it Take for God to Get Your Atten...308 David Displeased the Lord 309 What Will it Take for God to Get Your Atten...
308 David Displeased the Lord 309 What Will it Take for God to Get Your Atten...
 
Homosexuality and Ordination of Woman
Homosexuality and Ordination of WomanHomosexuality and Ordination of Woman
Homosexuality and Ordination of Woman
 
Jude: The Acts of the Apostates: Waterless Clouds (vv.8-13).pptx
Jude: The Acts of the Apostates: Waterless Clouds (vv.8-13).pptxJude: The Acts of the Apostates: Waterless Clouds (vv.8-13).pptx
Jude: The Acts of the Apostates: Waterless Clouds (vv.8-13).pptx
 
Surah Al-Mulk: Lessons on Guidance and Mercy
Surah Al-Mulk: Lessons on Guidance and MercySurah Al-Mulk: Lessons on Guidance and Mercy
Surah Al-Mulk: Lessons on Guidance and Mercy
 
Catechism_05_Blessed Trinity based on Compendium CCC.pptx
Catechism_05_Blessed Trinity based on Compendium CCC.pptxCatechism_05_Blessed Trinity based on Compendium CCC.pptx
Catechism_05_Blessed Trinity based on Compendium CCC.pptx
 
Spirituality: Beyond Dogmatic Texts - Audio Book
Spirituality: Beyond Dogmatic Texts - Audio BookSpirituality: Beyond Dogmatic Texts - Audio Book
Spirituality: Beyond Dogmatic Texts - Audio Book
 

Mutual Exclusion

  • 1. Reminder: Project Ideas are due by 11:59pm tonight!
  • 2. Plan for Today Recap: Dijkstra’s Mutual Exclusion Problem Why Obvious Solutions Fail Practical Solutions with Modern Processors Dijkstra’s Solution Lamport’s Solution 1 Reminder: Project Ideas are due by 11:59pm tonight!
  • 3. 2
  • 5. 4
  • 7. 6 Lessons for your Project Submissions: 1. Don’t submit something I will think is a decoy project! (Too late for that here) 2. Don’t do something that involves breaking into my house. 3. Do do something creative and unexpected.
  • 8. 7 T2 T3 T4T1 N independent threads Shared Memory (atomic read and write) T5 Program: loop { non-critical { … } critical { … } } Requirements: 1. Only one thread may be in the critical section at any time. 2. Each must eventually be able to enter its critical section. 3. Must be symmetrical (all run same program). 4. Cannot make any assumptions about speed of threads.
  • 9. Clever “Cheating” Solution 8 loop { if turn == i: critical_section; turn = i + 1; } T2 T3T1 Shared Memory turn: Initially, turn = 1
  • 10. 9 loop { if turn == i: critical_section; turn = i + 1; } Initially, turn = 1
  • 11. Attempted Solution 10 loop { if not lock: lock = true; critical_section; lock = false; } T2 T3T1 Shared Memory lock:
  • 12. Attempted Fix 11 loop { if lock == 0: lock = i; if lock == i: critical_section; lock = 0; } T2 T3T1 Shared Memory lock:
  • 13. Attempted Fix of Fix 12 loop { if lock1 == 0: lock1 = i; if lock1 == i: if lock2 == 0: lock2 = i; if lock2 == i: critical_section; lock2 = 0; lock1 = 0; } T2 T3T1 Shared Memory lock1: lock2:
  • 14. Attempted Fix of Fix of Fix … 13 loop { if lock1 == 0: lock1 = i; if lock1 == i: if lock2 == 0: lock2 = i; if lock2 == i: critical_section; lock2 = 0; lock1 = 0; } T2 T3T1 Shared Memory lock1: lock2: Do we need to see why 3-locks still breaks?
  • 15. Uniprocessor Easy (Kernel Cheating) Solution 14 loop { non-critical; disable interrupts critical_section; enable interrupts } T2 T3T1 Shared Memory
  • 18. Uniprocessor Easy (Kernel Cheating) Solution 17 loop { non-critical; disable interrupts critical_section; enable interrupts } T2 T3T1 Shared Memory How well does this solution work for modern kernels?
  • 19. Easy (Cheating) Solution 18 T2 T3T1 Shared Memory (with atomic read/write/test&set) lock: test_and_set(v) returns current value of v sets value of v to true
  • 20. Easy (Cheating) Solution 19 loop { if not test_and_set(lock): critical_section; lock = false; } T2 T3T1 Shared Memory (with atomic read/write/test&set) lock: test_and_set(v) returns current value of v sets value of v to true
  • 21. Does your processor provide such an instruction? 20
  • 24. 23
  • 25. Implementing a Mutex Lock 24 lock_mutex(lock); critical unlock_mutex(lock); LDREX <dest> <location> <dest> = <location> Sets monitor on <location> in Exclusive state STREX <success> <value> <location> Conditionally store <value> into exclusive <location>. If permitted, <success> = 1 and <location> = <value>. If not, <success> = 0 and <location> value unchanged. Context switch clears monitor (Open) state.
  • 26. 25 lock_mutex(lock); critical unlock_mutex(lock); lock_mutex(lock): try_again: LDREX R2, [lock] if R2 goto try_again STREX R2, 1, [lock] if not R2 goto try_again unlock_mutex(lock): STR [lock], 0 LDREX <dest> <location> <dest> = <location> Sets monitor on <location> in Exclusive state STREX <success> <value> <location> Conditionally store <value> into exclusive <location>. If permitted, <success> = 1 and <location> = <value>. If not, <success> = 0 and <location> value unchanged.
  • 27. 26 lock_mutex(lock); critical unlock_mutex(lock); lock_mutex(lock): try_again: LDREX R2, [lock] if R2 goto try_again STREX R2, 1, [lock] if not R2 goto try_again unlock_mutex(lock): STR [lock], 0 What if you care about energy?
  • 28. 27
  • 29. 28 WFE and WFI do not provide synchronization! Just hints to the processor to save energy.
  • 30. 29 ARMv7 Why two instructions like this instead of one?
  • 31. 30 T2 T3 T4T1 Shared Memory (atomic read and write) T5 Program: loop { non-critical { … } critical { … } } Requirements: 1. Only one thread may be in the critical section at any time. 2. Each must eventually be able to enter its critical section. 3. Must be symmetrical (all run same program). 4. Cannot make any assumptions about speed of threads. no special combined atomic operations (e.g., test-and-set, LDREX/STREX)
  • 32. 31 Dijkstra (1973) From Edgar Daylight’s collection: http://www.dijkstrascry.com/node/59 1965
  • 33. 32
  • 34. 33 Program for Processor i loop { b[i] := false L1: if k != i c[i] := true if b[k] k := i goto L1 else: c[i] := false for j in [1, …, N]: if j != i and not c[j]: goto L1 critical section; c[i] := true b[i] := true } Initialization b[1:N] = [true, true, …] c[1:N] = [true, true, …] k = choose([1..N])
  • 35. 34 Safety: only one program can be in critical section Program for Processor i loop { b[i] := false L1: if k != i c[i] := true if b[k]: k := i goto L1 else: c[i] := false for j in [1, …, N]: if j != i and not c[j]: goto L1 critical section; c[i] := true b[i] := true }
  • 36. 35 Program for Processor i loop { b[i] := false L1: if k != i c[i] := true if b[k]: k := i goto L1 else: c[i] := false; L4: for j in [1, …, N]: if j != i and not c[j]: goto L1 critical section; c[i] := true b[i] := true } How do we know none of the c[.]’s changed during the loop?
  • 37. Charge Think about Dijkstra’s Solution: How does it guarantee mutual exclusion? How does it guarantee liveness? Submit Project Idea by 11:59pm Tonight 36