lec6-process4 · mutual exclusion –hardware support qspecial machine instructions qexchange...
TRANSCRIPT
Process Synchronization
CSC501 Operating Systems Principles
1
Last Lecture
q Process Scheduling
Question I: Within one second, how many times the timer
interrupt will occur?
Question II: Within one second, how many times the resched()
will be called?
2
A Bug in resched()
3
Outline
q Why synchronization?q Semaphore
4
Race Condition
while (1) {while (count == BUFFER_SIZE)
/* noop */;// produce an item and put in nextbuffer[in] = nextProduced;in = (in + 1) % BUFFER_SIZE;count++;
}
while (1) {while (count == 0)
/* noop */;next = buffer[out];out = (out + 1) % BUFFER_SIZE;count--;// consume the item in next
}
Race Condition
q count++ could be implemented as
register1 = countregister1 = register1 + 1count = register1
Producer: Consumer: Values:register1 = count {register1 = 5}register1 = register1 + 1 {register1 = 6}
register2 = count {register2 = 5} register2 = register2 – 1 {register2 = 4}
count = register2 {count = 4}count = register1 {count = 6}
q count-- could be implemented as
register2 = countregister2 = register2 - 1count = register2
Initially, count = 5 6
Example: Shared Linked List(1) n->next = p->next(2) p->next = n
Order: a b 1 2
(a) m->next = p->next(b) p->next = m
p
n m
X
X
Example: Shared Linked List(1) n->next = p->next(2) p->next = n
Order: a 1 2 b
(a) m->next = p->next(b) p->next = m
p
n m
X
X
Race Condition
q A race condition occurs when Q Multiple processes or threads read and write
shared data items Q They do so in a way where the final result
depends on the order of execution of the processes.
9
Race Conditionq The existence of critical sectionQ A section of code within a process that requires
access to shared resources and that must not be executed while another process is in a corresponding section of code
q Why should we care?Q Concurrent access to shared data may result in
data inconsistency
10
Race Conditionq The existence of critical sectionQ A section of code within a process that requires
access to shared resources and that must not be executed while another process is in a corresponding section of code
q Necessary conditionsQ ConcurrencyQ Shared dataQ Interference
Question: How to achieve concurrency of multiple processes/threads on
shared data without interference?
11
Solution to Critical-Section Problemq Mutual Exclusion Q If process Pi is executing in its critical section,
then no other processes can be executing in their critical sections
q Two other follow-up problemsQ DeadlockQ Starvation
ProgressBounded Waiting
12
Mutual Exclusion – Hardware Support
q Interrupt disablingQ E. g., cti/sti
while (true) {/* disable interrupts */;/* critical section */;/* enable interrupts */;/* remainder */;
}
13
Mutual Exclusion – Hardware Support
q Special machine instructionsQ Exchange instruction (e.g., xchg)Q Compare&Exchange instruction
void exchange (int register, int memory){
int temp;temp = memory;memory = register;register = temp;
}Statements are
executed atomically
int keyi = 1;do
exchange(keyi, lock);while (keyi!=0)
/* critical section */;lock = 0;/* remainder */;
}
spinlock
Question: In a single CPU environment,
do we need spinlock?14
Mutual Exclusion – Hardware Support
q AdvantagesQ It is simple and therefore easy to verifyQ Applicable to any number of processes sharing main
memoryQ It can be used to support multiple critical sections
q DisadvantagesQ Busy-waiting consumes processor timeQ Starvation is possible Q Deadlock is possiblev E.g., priority-driven preemptive scheduling
15
Mutual Exclusion – Software Support
q Semaphore: Q An integer value used for signalling among
processes. Q Three operations, each of which is atomic:v initializev decrementn P, wait, semWait, or acquire
v incrementn V, signal, semSignal, or release
16
qCounting semaphoreQ An integer value can range over an unrestricted
domainqBinary semaphoreQ An integer value can range only between 0 and 1;
can be simpler to implementQAlso known as mutex locks
Semaphore S; // initialized to 1acquire(S);criticalSection();release(S);
Semaphore
17
Semaphore
sys/ in Xinu: screate.c sdelete.c wait.c signal.csys/ in Xinu: screate.c sdelete.c wait.c signal.c
18
Strong/Weak Semaphore
q A queue is used to hold processes waiting on the semaphoreQ In what order are processes removed from the
queue?q Strong Semaphores use FIFOq Weak Semaphores don’t specify the order of
removal from the queue
19
Example of Strong Semaphore
20
Example of Semaphore Mechanism
21
Semaphore Implementationq Must guarantee that no two processes can execute
acquire() and release() on the same semaphore at the same time
q Thus implementation becomes the critical section problemQ Busy waiting (spinlock) in critical section implementationv Implementation code is shortv Little busy waiting if critical section rarely occupiedv More busy waiting à waste of CPU resources
Q Applications may spend lots of time in critical sectionsv Performance issues need to be addressed
22
Mutual Exclusion – Software Support
q AdvantagesQ It is simple and therefore easy to verify?Q It can be used to support multiple critical sections?
q DisadvantagesQ Starvation is possible?Q Deadlock is possible?
Hardware-based mutual exclusion
Software-based mutual exclusion
23
q Deadlock – two or more processes are waiting indefinitely for an event that can be caused by only one of the waiting processes
q Let S and Q be two semaphores initialized to 1P0 P1
acquire(S); acquire(Q);acquire(Q); acquire(S);. .. .. .
release(S); release(Q);release(Q); release(S);
q Starvation – indefinite blocking. A process may never be removed from the semaphore queue in which it is suspended
Deadlock and Starvation
24
Classical Problems of Synchronization
q Bounded-Buffer Problemq Readers and Writers Problemq Dining-Philosophers Problem
25
Bounded Buffer
q Buffer has limited slotsq Producer waits if buffer fullq Consumer waits if buffer empty
N producers
M consumers
width
26
Semaphore solution
public void insert (Item item){empty.acquire();mutex.acquire();
// add an item to the bufferbuffer[in] = item;in = (in + 1) % N;
mutex.release();full.release();
}
Item buffer[N]; int in = 0, out = 0; Semaphore mutex = 1;Semaphore empty = N; // count empty slotsSemaphore full = 0; // count full slots
public Item Remove(){full.acquire();mutex.acquire();
// remove an item item = buffer[out];out = (out + 1) % N;
mutex.release();empty.release();return item;
}
Question: How about single producer /consumer?
Readers and Writers Problem
q Protect shared data or databaseQ A writer has exclusive access to data (no other
concurrent writers or readers)Q Readers can have concurrent access (allow
multiple readers)q FormallyQ nw = # of active writersQ nr = # of active readersQ Safety condition: (nr = 0 or nw = 0) and nw <= 1
28
Solution using Semaphores
int nr = 0;Semaphore mutex = 1,
db = 1;
writer() {while (1) {
P(db)// write
V(db)}
}
reader() {while (1) {
P(mutex)nr++if (nr == 1) P(db)V(mutex)
// readP(mutex)nr--if (nr == 0) V(db)V(mutex)
}}
Solution using Semaphores
int nr = 0;Semaphore mutex = 1,
db = 1;
writer() {while (1) {
P(db)// write
V(db)}
}
reader() {while (1) {
P(mutex)nr++if (nr == 1) P(db)V(mutex)
// readP(mutex)nr--if (nr == 0) V(db)V(mutex)
}}
Solution using Semaphores
q What is the use of:Q mutex?Q db?
31
Dining-Philosophers Problemq5 philosophers: Think, or EatQNeeds two forks to eat, one from each side
qShared data Semaphore fork[] = new Semaphore[5];
32
Semaphore solutionSemaphore forks[5] =
{1,1,1,1,1}
philospher(int i) {while (1) {fork[i].acquire(); fork[(i+1)%5].acquire();eat;fork[i].release(); fork[(i+1)%5].release();think;
}}
q Problem deadlockQ How?
q SolutionQ Allow at most 4 sittingQ Allow one to pick up only
if both forks available (pick both in CS)
Q Break symmetry, e.g., an odd person picks up left first, and even person picks up right first
Next Lecture
q Process Synchronizationq Lab0
34