

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


CS 326 Operating Systems Greg Benson 1
2
3
lock_acquire(struct *lk) { int acquired = 0; while(!acquired) { disable_preemption(); if (lk->value == UNLOCKED) { acquired = 1; lk->value = LOCKED; } enable_preemption(); } } lock_release(struct *lk) { lk->value = UNLOCKED; } 4
int acquired = 0; while(!acquired) { ! disable_preemption(); ! if (lk->value == UNLOCKED) { acquired = 1; lk->value = LOCKED; ! } else { listadd(lk->list, cur); thread_block(); ! } enable_preemption(); } } lock_release(struct *lk) { disable_preemption(); lk->value = UNLOCKED; if (!listempty(lk->list)) { thread_unblock(listremove(lk->list); } enable_preemption(); 5 }
we keep the critical sections short
or impossible in some cases (e.g., user-level code)
high-level synchronization
conditional 6
Test-And-Set Instruction ! Hardware support for atomic read and modify ! C version: int test_and_set(int *target) { int tmp; tmp = target; / get cur value / target = 1; / set to 1 / return tmp; / return prev value/ } 7 Multiprocessor Locking ! We can use test-and-set to implement a multiprocessor lock ! Assume 0 means UNLOCKED and 1 means LOCKED int lock; lock_acquire(int lock) { while (test_and_set(lock)); / loop */ } lock_release(int *lock) { lock = 0; } 8 Multiprocessor Locking Try 2 ! The test-and-set instruction is expensive on most processors because it generates a lot of traffic on the bus and/or between processors ! Optimization: int lock; lock_acquire(int lock) { while (test_and_set(lock)) { while (lock); / loop */ } } lock_release(int *lock) { *lock = 0; } 9 Multiprocessor Locking Try 3 ! In some cases it might be efficient to have a thread “spin” waiting for a lock (e.g., no other thread ready to run on a processor) ! If other threads present, then it is best to spin then block ! Basic idea ! Determine cost to block (block_time) ! Spin for block_time, then block ! Worst case cost: (2 * block_time) 10