Section notes for CS162 Section #3, February 12, 2002 Barbara Hohlt - Critical Section, a piece of code that only one thread can execute at once. Only one thread at a time will get into the section of code. - Synchronization Requirements - Mutual Exclusion, ensuring only one thread can execute in a critical section at a time - Progress, one thread must always be allowed to enter the critical section - Bounded waiting, a thread should not wait indefinitely to enter its critical section - Locks are used to implement mutual exclusion. All require some level of hardware support. - Atomic operations are a set of instructions which execute as one uniterruptible unit. TestAndSet and Swap are atomic operations supported by most hardwares. /* returns the current value of lock and sets lock to true */ TestAndSet(lock) TestAndSet = lock lock = true /* swaps two values Swap(local(i), lock) temp = lock; lock = local(i) local(i) = temp ------------------------------------------------------------------------ - Critical Section Problem using TestAndSet ------------------------------------------------------------------------ global var waiting: array[0...n-1] of boolean, init to false; lock: boolean, init to false; local var j: 0...n-1; key: boolean; waiting[i] = true; /* Thread i */ key = true; while waiting[i] and key do key = TestAndSet(lock); waiting[i] = false; CRITICAL SECTION... j = j + 1 mod n; while (j != i) and (not waiting[j]) do j = j + 1 mod n; if j = i then lock = false else waiting[j] = false; I will use a "dressing room" analogy to explain this code. We have a dressing room (critical section), a lock, and a queue of people waiting on the dressing room (key is just a local variable). Only one person can be in the dressing room at a time. I (thread i) am waiting for the dressing room as long as there is someone in the dressing room (lock == true) AND I am waiting for the dressing room (waiting[i] == true). When someone leaves the dressing room they tell the next person on the queue (waiting[j] == false) OR IF NO ONE IS WAITING they unlock the dressing room (lock == false). ------------------------------------------------------------------------ - Locks, condition variables, semaphores, interrupts, atomic ops - Locks: implement mutual exclusion - Condition variables: make it possible to go to sleep inside a critical section by atomically releasing a lock at the same time the thread goes to sleep - Semaphores: a generalized lock, having a non-negative integer value (classical definition) - Interrupts: an external event which causes the dispatcher to take the CPU away - These things can be built out of each other - Use semaphores to implement condition variables - Use interrupts to implement condition variables (uniprocessor) - Use semaphores to implement a lock - Use interrupts to implement a lock (uniprocessor) - Use TestAndSet to implement a lock