synchronization
DESCRIPTION
introduction to semaphoresTRANSCRIPT
PowerPoint Presentation
SynchronizationOperating System Concepts
Semaphores
Ahmad Uways ZulkurnainContentsReview of race conditionsLibrary analogy to demonstrate resource contentionIntroduction to semaphoresReview: Race ConditionsThread 1:Thread 2:a = data;a = a+1;data = a; b = data;b = b + 1;data = b;
Resulting value of data?Review: Race ConditionsScenario 1
Thread 1 Thread 2 dataa = data;---0a = a+1;---0data = a;---1---b = data;1---b = b + 1;1---data = b;2Review: Race ConditionsScenario 2
Thread 1 Thread 2 dataa = data;---0a = a+1;b = data;0data = a;---1---b = b + 1;1---data = b;1Solutions?LocksHardware based atomic operations*Software based language support*sequence of one or more machine instructions that are executed sequentially, without interruption
What about resources that can handle multiple, but limited number of users simultaneously?
A library has x study rooms, used by one student at a timeStudents must request a room from the front deskIf no rooms are free, students wait at the desk until one is free. When finished with a room, the student must return to the desk and indicate that one room has become free.
Library Analogy
emptyLibrary AnalogyWhat is known:Number of free roomsWhat is not known:which rooms are occupiedwho is using themIf a room is actually being used
Library AnalogyStudy rooms resourcesStudents processesFront desk semaphore
emptySemaphoresBy E.W. Dijkstra (1930-2002)Published in paper On the sequentiality of process descriptions 1962/63
SemaphoresSynchronization toolSemaphore, Sinteger variableatomic increment and decrementwaiting listTwo standard operations modify Swait()signal()S can only be accessed by wait() and signal()Semaphorestypedef struct{ int value; process *list;} semaphore;
wait(S) {} signal(S) {}block() {} wakeup(P) {}
wait()Decrements S valueIf the value is negative, adds requesting process to waiting list and blocks the requesting process
wait(semaphore *S) { S->value--; if (S->value < 0) { add process to S->list; block(); }}signal()Increments S valueIf the value is not positive, removes a process from waiting list and wakes it up
signal(semaphore *S) { S->value++; if (S->value list; wakeup(P); }}Types of SemaphoresCounting semaphoreBinary semaphoreValue can be only 1 or 0Known as mutexConstructed from counting semaphore by initializing value to 1Provides mutual exclusionBinary Semaphoresemaphore mutex(1);
while(TRUE) { wait(mutex); // critical section of code to lock signal(mutex); // continue code}
Does not require busy waitingApplications of SemaphoresBounded-Buffer ProblemReaders and Writers ProblemDining-Philosophers Problem