Locks & Race Conditions Flashcards
Synchronization in Share Memory
Shared Memory Synchronization
(Critical Section)
Region of code that accesses variables that are shared between threads.
Shared Memory Synchronization
(Shared Resource)
can be anything of interest: bank balance, data structure, device, network connection. Always represented in memory, so we can talk equivalently in terms of Shared Variables.
Example: Banking
Two threads called update on the same bank account. The code inside update is the critical region, the shared variable being bal.
Problem: Banking
Final result may be that the balance is 5 instead of 10
This is a lost update problem.
Problem Source
update of bank account is not atomic, meaning that when one thread is in the middle of updating a bank account, another thread may start updating the same account
Problem Nature: Race Condition
The condition where an incorrect program output may be generated depending on the relative order in which instructions from multiple threads are interleaved (executed).
Threads Introduce Nondeterminism
- Sequential programs are deterministic: for the same input, the same output
- Threads make a program nondeterministic:
- For the same input, output depends on the interleaving of instructions from different threads. Race condition if output can be incorrect.
- Aim of synchronization: Eliminate race conditions
- Correct output? One influential idea is that any output from interleaving multiple threads is the same as an output from executing the threads sequentially.
- Atomicity of a critical section means that only one thread may be in it and the thread must finish the section before another thread may enter, thus ensuring “sequentiality.”
Locks: Solving Banking Problem via Mutual Exclusion
Mutual exclusion for a resource: limits resource access to one thread at a time. Guarantees atomicity.
Lock can be in one of two states
– Held: A thread is in the critical section (no other thread can enter)
– Not held: No thread in the critical section (any thread can enter)
Two operations to move lock between states
– Acquire: mark lock as held, or wait until release
– Release: mark as not held
lock_example()
Lock Declaration
Declared like a variable
– Lock L;
Programs can have multiple locks
– Lock L, P;
– Call acquire at start of critical section
– Call release at end of critical section
– Achieves mutual exclusion and progress
Acquisition of a lock blocks only threads attempting to acquire the same lock.
Must use same lock for all critical sections accessing the same resource
Mutual Exclusion in Java
Every Java object has an implicit (i.e. invisible) lock
Lock is achieved via the synchronized block
– Prevents thread entry to block until lock acquisition
– Lock release on block completion so other threads enter
Locks in Java - Method
Locks in Java – Code Block
Bank_account in action