Critical Section Ch3
Critical Section Ch3
1 2
3 4
5 6
1
Correctness for systems with concurrent
Multiprocessing vs Multiprogramming threads
• Remember Definitions: • If dispatcher can schedule threads in any way,
– Multiprocessing Multiple CPUs programs must work under all circumstances
– Multiprogramming Multiple Jobs or Processes – Can you test for this?
– Multithreading Multiple threads per Process – How can you know if your program works?
• What does it mean to run two threads “concurrently”? • Independent Threads:
– Scheduler is free to run threads in any order and – No state shared – separate address space
interleaving: FIFO, Random, … – Deterministic Input state determines results
– Dispatcher can choose to run each thread to completion – Reproducible Can recreate Starting Conditions, I/O
or time-slice in big chunks or small chunks
– Scheduling order doesn’t matter (if switch() works!!!)
A • Cooperating Threads:
Multiprocessing B – Same address space, shared state between multiple
C
threads
– Non-deterministic
A B C
– Non-reproducible
• Non-deterministic and Non-reproducible means that
Multiprogramming A B C A B C B bugs can be intermittent
– Sometimes called “Heisenbugs”
7 8
9 10
11 12
2
Critical Section Critical Section (CS) Problem
• Section of code that: • Provide entry and exit routines
– Must be executed by one thread at a time – All threads must call entry before executing
– If more than one thread executes at a time, CS.
have a race condition – All threads must call exit after executing CS
– Ex: linked list from before – Thread must not leave entry rounte until it’s
• Insert/Delete code forms a critical section safe.
• What about just the Insert or Delete code?
13 14
13 14
15 16
17 18
3
Critical Section Solution Attempt #1 Critical Section Solution Attempt #2
(2 thread solution) (2 thread solution)
Intially, turn == 0 Intially, flag[0] == flags[1] == false
exit(id) { exit(id) {
turn = 1 - id; /* other thread’s turn*/ flag[id] = false; /* I am out*/
} }
19 20
19 20
21 22
23 24
4
Atomic Operation Test-and-Set
• An operation that, once started, runs to • Many machines have it
completion
• Indivisible bool TestAndSet(bool &target) {
• Ex: loads and stores bool b = target;
– Meaning: if thread A stores “1” into variable x target = true;
and thread B stores “2” into variable x about return b;
the same time, result is either “1” or “2”. }
25
• Executes atomically 26
25 26
27 28
29 30