Lecture 8: Synchronisation in Parallel Programming - Locks and Barriers, Condition Variables, Lecture 9: More about locks Flashcards
What are barriers, locks and condition variables used for?
Barriers: simple mechanism letting threads wait for each other (pthread barrier)
Locks: allowing threads to safely access shared data (prevent concurrent access)
Condition variables: for event signalling between threads
When are barriers used?
- Want the whole answer from this step before proceeding to the next step
- Would also use when data dependence limits loop parallelisation
What is the term for
Concurrent operations on shared state should not happen at the same time
Race condition
What is the term for
Bits of code in our program where shared data is accessed/updated
Critical sections
What do locks ensure?
Serialisation: amount of threads that can concurrently execute it (generally 1)
Atomicity: when a thread T starts to run a critical section S, T must first finish S before another thread can enter S
What is the term for
Synchronisation primitive enforcing limits on the execution of a critical section
Lock
True or False
Multiple threads can hold a given lock at a time
False
What is a mutex?
Mutual exclusion lock
pthread_mutex
What is an example of lock usage? Why is it important?
Bounded buffer: circular FIFO producer-consumer buffer.
If locks are not used:
1. Could have two threads writing (deposit) to or reading (extract) from the same element of buffer, and one value is lost. 2. Could then either increment in_index
Once: whole call of deposit() lost
Twice: spurious (old) value apparently deposited
Benefits and drawbacks of usleep?
With the usleep set to an arbitrary time, may sleep for a much longer time than needed
Without usleep, keep trying non-stop, monopolising the CPU and wasting cycles
What are condition variables?
Used to signal threads (event signalling) waiting for a conjunction of:
1. A lock becoming free and
2. An arbitrary event (e.g. buffer becoming non-full)
pthread_cond_wait, pthread_cond_signal
What are some issues with locks?
- Deadlock
- Lost wakeup issue
How can lost wakeup occur? How can it be solved?
Implementation details, timing, or race conditions in the signaling mechanism
Wake up all threads (vs. a single thread) waiting on a condition variable
Why is it important to get your synchronisation strategy right from the beginning?
Concurrency issues are hard to debug
What determines how big a chunk of code which depends on obtaining a lock should you write?
Granularity