Lecture09 ConcurrentProgramming 02 Synchronization
Lecture09 ConcurrentProgramming 02 Synchronization
Synchronization
Computer Systems Organization (Spring 2016)
CSCI-UA 201, Section 2
Not so fast
Sharing variables is actually useful thing when programming threads
Global variables are not the only variable type that can be shared.
Example of Sharing
Local variables
Definition: Variable inside function without static attribute
Each thread stack contains one instance of each local variable
ptr
cnt
main.i
main.msgs
p0.i
p1.i
Referenced by
main thread?
yes
no
yes
yes
no
no
Referenced by
peer thread 0?
yes
yes
no
yes
yes
no
Referenced by
peer thread 1?
yes
yes
no
yes
no
yes
Synchronizing Threads
Shared variables are sometimes useful but they introduce the
possibility of synchronization errors.
Like the one we saw last time
11
12
Mutual Exclusion
A mutex
is synchronization variable that is used to protect the access to shared variables.
surrounds critical sections so that one threads is allowed inside at a time.
13
14
15
16
17
Fine-grained Locking
18
19
Deadlock
The following series of instructions happened
20
Deadlock cont
Both processes need resources to continue execution.
P1 requires additional resource R1 and is in possession of
resource R2
P2 requires additional resource R2 and is in possession of R1;
neither process can continue.
21
Dining Philosophers
Five philosophers
Goal in life: eat, think, eat,
think, eat, think, ...
Five bowls of spaghetti
Five forks
But need two forks to eat
22
23
Condition Variables
Locking is a simple kind of resource scheduling -- one thread at a time
may enter a critical section.
What about more complicated scheduling policy?
Supposed we need a mechanism to block thread(s) until some condition is true?
24
Waiting on a Condition
For example, suppose we want one function in one thread to produce a
value and another function on another thread to consume that value?
25
26
27
See cond_var.c
29
Summary
30