Locks vs Latches
Locks | Latches | |
---|---|---|
Separate… | User transactions | Threads |
Protect… | Database Contents | In-Memory Data Structures |
During… | Entire Transactions | Critical Sections |
Modes… | Shared, Exclusive, Update, Intention | Read, Write |
Deadlock | Detection & Resolution | Avoidance |
…by… | Waits-for, Timeout, Aborts | Coding Discipline |
Kept in… | Lock Manager | Protected Data Structure |
Test and Set Spin Latch (TAS)
A spin latch is essentially a location in memory that threads try to update
- Example:
std::atomic<T>
- Advantages: Latch/unlatch operations are efficient (single instruction to lock/unlock on x86, CAS).
Blocking OS Mutex
Linux provides the futex (fast user-space mutex), which is comprised of (1) a spin latch in user-space and (2) an OS-level mutex.
If the DBMS can acquire the user-space latch, then the latch is set. It appears as a single latch to the DBMS even though it contains two internal latches. If the DBMS fails to acquire the user-space latch, then it goes down into the kernel and tries to acquire a more expensive mutex. If the DBMS fails to acquire this second mutex, then the thread notifies the OS that it is blocked on the mutex and then it is de-scheduled.
- Example: std::mutex
- Advantages: Simple to use and requires no additional coding in DBMS.
Reader Writer Latches
- Example: std::shared mutex
- Advantages: Allows for concurrent readers.
- Disadvantages: The DBMS has to manage read/write queues to avoid starvation. Larger storage overhead than spin Latches due to additional meta-data.