100 likes | 150 Views
This lecture delves into the critical concept of atomic execution without interruption in programming. Learn about sources of interruption like hardware interrupts and thread pre-emption, and tools such as TestAndSet and Turn-off interrupts in TAS. Discover the importance of coordination and condition variables in maintaining atomicity and avoiding races. Gain insights into coordinating sequences in multithreaded programming for efficient and error-free code execution.
E N D
Coordination 6.894 Lecture 5
Why Coordinate? • Critical section: • Must execute atomically, without interruption. • Atomicity usually only w.r.t. other operations on the same data structures. • What are sources of interruption? • Hardware interrupts, UNIX signals. • Thread pre-emption. • Interleaving of multiple CPUs.
Tools for Atomicity (1) • If this worked, we would be done: TestAndSet(int *addr){ int old = *addr; *addr = 1; return(old); } insert(…){ while(TestAndSet(&locked) == 1) ; /* critical section goes here */ locked = 0; }
Tools for Atomicity (2) • Turn off interrupts in TAS to avoid race. • Prevents pre-emption via real-time clock. • Only in the kernel, only on a uniprocessor. • Kernel emulation of TestAndSet. • Only on a uniprocessor. • Test-And-Set-Locked hardware support.
Test-And-Set-Locked Instruction • Single instruction to do this: int old = *addr; *addr = 1; return(old); • The hardware locks the memory system to keep the two sub-operations atomic. • TSL lets us build more complex atomic sequences. • See Example 3 for a simple one.
Problems with TSL • Operates at motherboard speeds, not CPU. • Much slower than cached load or store. • Prevents other use of the memory system. • Interferes with other CPUs and DMA. • Silly to spin in TSL on a uniprocessor. • Add a thread_yield() after every TSL.
Locks Aren’t Enough • Summary of code Example 4: • Consumer: • If(input isn’t ready) sleep(); • Producer: • If(consumer is waiting) wake it up; • What’s the problem? • Can we solve the problem with locks alone?
Sequence Coordination • Need to avoid races between decision to sleep and actual sleep(). • Can’t hold lock while sleeping. • Need the thread scheduler to help us release the lock. • Common abstraction: condition variables. • Code Examples 5 and 6.
Condition Variable Rules • Hold the lock while calling wait(). • Hold the lock while calling signal(). • wait() acquires the lock before returning.