Critical Section Problem: CIS 450 Winter 2003
Critical Section Problem: CIS 450 Winter 2003
Context Switching
Switching between 2 threads
Change PC to current instruction of new thread
might need to run old thread in the future
Must save exact state of first thread State saved into the TCB
Hybrid Implementations
Cooperating threads
Same address space Can affect one another Must be careful!
Race Condition
This kind of bug, which only occurs under certain timing conditions, is called a race condition. Output depends on ordering of thread execution More concretely:
(1) two or more threads access a shared variable with no synchronization, and (2) at least one of the threads writes to the variable
10
Critical Section
Section of code that:
Must be executed by one thread at a time If more than one thread executes at a time, have a race condition Ex: linked list from before
Insert/Delete code forms a critical section What about just the Insert or Delete code?
11
12
/* I am out*/
16
Absence of deadlock
turn must be 0 or 1 => one thread will be allowed in
Bounded Waiting
spinning thread will not modify turn thread trying to go back in will set turn equal to spinning thread
18
19
Hardware Support
Provide instruction that is:
Atomic Fairly easy for hardware designer to implement
Read/Modify/Write
Atomically read value from memory, modify it in some way, write it back to memory
Use to develop simpler critical section solution for any number of threads.
20
Atomic Operation
An operation that, once started, runs to completion Indivisible Ex: loads and stores
Meaning: if thread A stores 1 into variable x and thread B stores 2 into variable x about the same time, result is either 1 or 2.
21
Test-and-Set
Many machines have it
bool TestAndSet(bool &target) { bool b = target; target = true; return b; }
Executes atomically
22
exit() { S = false; }
23
When done with CS, set shared varible back to initial state.
24