80 likes | 185 Views
Explore the nuanced world of concurrent programming through an examination of thread interactions. In this scenario, two threads operate on a shared variable `v`, with one thread incrementing and the other decrementing, leading to various potential outcomes for `v`. We delve into the principles of mutual exclusion, addressing key conditions and historical algorithms such as Dekker's and Peterson's. Additionally, we discuss the role of hardware support with Test and Set Locks, highlighting their significance in avoiding busy waiting and ensuring proper synchronization in critical sections, particularly in the producer-consumer model.
E N D
Initially v=0. Thread 1: for (i=0; i<10; i++) v = v+1; Thread 2: for (i=0; i<10; i++) v = v-1; Concurrent Threads What are the possible values of v at the end? Cpr E 308, Fall 2003
Mutual Exclusion so far Four conditions to provide mutual exclusion • No two processes simultaneously in critical region • No assumptions made about speeds of CPUs • No process running outside its critical region may block another process • No process must wait forever to enter its critical region Cpr E 308, Fall 2003
Solutions to Mutual Exclusion • Dekker’s Algorithm – 1960’s • Peterson’s Algorithm – 1981 • Hardware support Cpr E 308, Fall 2003
Peterson’s Solution Cpr E 308, Fall 2003
Hardware Support with TSL • Instruction TSL R, LockTSL = “Test and Set Lock”R = register, Lock = memory location • Atomic = “all or nothing” • Atomically- reads Lock into R and - Store a non-zero value into Lock Cpr E 308, Fall 2003
Mutual Exclusion using TSL • Problems: • Busy Waiting, • Not very useful on a uniprocessor Cpr E 308, Fall 2003
Eliminate Busy Waiting Implementation of mutex_lock and mutex_unlock Without busy waiting Cpr E 308, Fall 2003
Producer - Consumer • Producer - Insert produced objects into bounder buffer • Consumer - Delete objects from the buffer and eat them • Synchronization required - Exclusive access to the buffer- Buffer full? - Buffer empty? Cpr E 308, Fall 2003