Threads & Multithreading: Continued
Threads & Multithreading: Continued
(Continued)
Thread Hazards
int a = 1, b = 2, w = 2;
main() {
CreateThread(fn, 4);
CreateThread(fn, 4);
while(w) ;
}
fn() {
What happens here?
int v = a + b; Lesson 7: Concurrency
w--;
}
Concurrency Problems
A statement like w-- in C (or C++) is implemented by several machine
instructions:
ld r4, #w
add r4, r4, -1
st r4, #w
Now, imagine the following sequence, what is the value of w?
Option 1: heap
allocate the stacks on the heap (using malloc)
easier, hazardous static data
code
stack
Option 2:
allocate the stacks away from the other segments
require OS support, safer
heap
static data
code
Other Hazards?
Disadvantages:
The scheduler gets invoked only when Yield is called with the
argument any (or when a thread blocks)
Depending on the thread package semantics, a thread could
yield the processor when it blocks for I/O
Non-Cooperative Threads