11 Locks
11 Locks
Implementing
Locks
Nima Honarmand
(Based on slides by Prof. Andrea Arpaci-Dusseau)
Fall 2017 :: CSE 306
• Correctness
• Mutual exclusion: only one thread in critical section at a time
• Progress (deadlock-free): if several simultaneous requests, must
allow one to proceed
• Bounded wait (starvation-free): must eventually allow each waiting
thread to enter
Building Locks
• Locks are variables in shared memory
• Two main operations: acquire() and release()
• Also called lock() and unlock()
Example: Test-and-Set
Semantic:
// return what was pointed to by addr
// at the same time, store newval into addr atomically
int TAS(int *addr, int newval) {
int old = *addr;
*addr = newval;
return old;
}
Implementation in x86:
int TAS(volatile int *addr, int newval) {
int result = newval;
asm volatile("lock; xchg %0, %1"
: "+m" (*addr), "=r" (result)
: "1" (newval)
: "cc");
return result;
}
Fall 2017 :: CSE 306
A B A B A B A B
• Awful when…
• one CPU
• locks held a long time
• disadvantage: spinning is wasteful
Fall 2017 :: CSE 306
A B C D A B C D
no yield: A B C D A B C D
yield: A A B
Spinning Performance
• Wasted time
• Without yield: O(threads × time_slice)
• With yield: O(threads × context_switch_time)
Blocking Locks
• acquire() removes waiting threads from run queue using
special system call
• Let’s call it park() — removes current thread from run queue
• release() returns waiting threads to run queue using special
system call
• Let’s call it unpark(tid) — returns thread tid to run queue
Race Condition
Thread 1 in acquire() Thread 2 in release()
if (l->lock) {
queue_add(l->q, gettid());
l->guard = 0;
while (TAS(&l->guard, 1) == 1);
if (queue_empty(l->q))
l->lock=false;
else
unpark(queue_remove(l->q));
park();
myself }
• Uniprocessor
• Waiting process is scheduled → Process holding lock can’t be
• Therefore, waiting process should always relinquish processor
• Associate queue of waiters with each lock (as in previous
implementation)
• Multiprocessor
• Waiting process is scheduled → Process holding lock might be
• Spin or block depends on how long before lock is released
• Lock is going to be released quickly → Spin-wait
• Lock released slowly → Block
Fall 2017 :: CSE 306
Two-Phase Locking
• A hybrid approach that combines best of spinning
and blocking
• Two cases:
• T < C: optimal would spin for T (cost = T), so do we (cost = T)
• T ≥ C: optimal would immediately block (cost = C), we spin for C and
then block (cost = C + C = 2C)
• So, our cost is at most twice that of optimal algorithm