Synchronization III: Summary CPE Operating Systems
Synchronization Topics Critical Section Limiting Concurrent Resource Access Sequencing Events
What’s wrong the code on the left? int Mutex = 1; while (Mutex == 0); Mutex--; // Critical Section Mutex++; Semaphore Mutex = 1; Wait (Mutex); // Critical Section Signal(Mutex);
Non-Atomic instruction Register1 = Mutex Decrease register1 Mutex = register1 Register2 = Mutex Decrease register2 Mutex = register2 Register1 = Mutex Register2 = Mutex Decrease register2 Mutex = register2 Decrease register1 Mutex = register1
Semaphore Wait(s)Signal(s)
Busy Waiting while (Mutex == 0);Wait (Mutex); Very high CPU load!
Semaphore vs Monitor
Critical Section Semaphore mutex=1; int count=0; void add() { wait(mutex); count++; signal(mutex); } int count=0; Monitor doStuff { Void add() { count++; }
Limiting Concurrent Resource Access Semaphore db=3; void connectDb() { wait(db); connect(); signal(db); } int MaxDb=3; Monitor doStuff { Void connectDb() { if (MaxDb > 0){ MaxDb--; connect(); MaxDb++; }
Sequencing Events Semaphore buffer=0; void consume() { wait(buffer); removeItem(); } Void Produce() { addItem(); signal(buffer); } Monitor doStuff { Condition buffer; Void consume() { if (bufferLen==0) buffer.wait(); removeItem(); } Void Produce() { addItem(); buffer.signal() }