lec6_sem - Review Critical Section CSE120 Principles of...

Info icon This preview shows pages 1–4. Sign up to view the full content.

1 CSE120 Principles of Operating Systems Prof Yuanyuan (YY) Zhou Lecture 6 Oct 12th , 2010 10/11/2010 CSE 120 – Lecture 5 – Synchronization 2 Review: Critical Section Process { while (true) { ENTER CRITICAL SECTION Access shared variables; // Critical Section; LEAVE CRITICAL SECTION Do other work } } 10/11/2010 CSE 120 – Lecture 5 – Synchronization 3 Using Locks What happens when blue tries to acquire the lock? Why is the “return” outside the critical section? What if not? What happens when a third thread calls acquire? withdraw (account, amount) { acquire(lock); balance = get_balance(account); balance = balance – amount; put_balance(account, balance); release(lock); return balance; } acquire(lock); balance = get_balance(account); balance = balance – amount; balance = get_balance(account); balance = balance – amount; put_balance(account, balance); release(lock); acquire(lock); put_balance(account, balance); release(lock); Critical Section 10/11/2010 CSE 120 – Lecture 5 – Synchronization 4 How do we implement locks? Here is one attempt: This is called a spinlock because a thread spins waiting for the lock to be released Does this work? Implementing Locks (1) struct lock { int held = 0; } void acquire (lock) { while (lock->held); lock->held = 1; } void release (lock) { lock->held = 0; } busy-wait (spin-wait) for lock to be released
Image of page 1

Info icon This preview has intentionally blurred sections. Sign up to view the full version.

2 10/11/2010 CSE 120 – Lecture 5 – Synchronization 5 Atomic Instructions: Test-And-Set The semantics of test-and-set are: Record the old value Set the value to TRUE Return the old value Hardware executes it atomically ! When executing test-and-set on “flag” What is value of flag afterwards if it was initially False? True? What is the return result if flag was initially False? True? bool test_and_set (bool *flag) { bool old = *flag; *flag = True; return old; } All atomically as one instruction 10/11/2010 CSE 120 – Lecture 5 – Synchronization 6 Using Test-And-Set Here is our lock implementation with test-and-set: When will the while return? What is the value of held? Does it work? Does it work on multiprocessors? struct lock { int held = 0; } void acquire (lock) { while (test-and-set(&lock->held)); } void release (lock) { lock->held = 0; } 10/11/2010 CSE 120 – Lecture 5 – Synchronization 7 Other Similar Hardware Instruction Swap = TSL void Swap (char* x,* y); \\ All done atomically { char temp = *x; *x = *y; *y = temp } Do it yourself Use Swap to implement lock acquire and release 10/11/2010 CSE 120 – Lecture 6 – Semaphores and Monitors 8 struct lock { int held = 0; } void acquire (lock) { } void release (lock) { } Fill in code here Fill in code here
Image of page 2