160 likes | 355 Views
Concurrent Processes. Producer-consumer problem. Producer producer of some resource Printer requests, lex in compiler, etc. Consumer Consumes items produced by producer Printer daemon that prints requests, syntax analyzer in compilers, etc. Bounder buffer problem.
E N D
Producer-consumer problem • Producer • producer of some resource • Printer requests, lex in compiler, etc. • Consumer • Consumes items produced by producer • Printer daemon that prints requests, syntax analyzer in compilers, etc.
Bounder buffer problem • Common buffer is accessed by both producer and consumer • Make sure that all items are consumed exactly once • All items consumed by the consumer are indeed produced by the produced
Correctness • Each item produced by the producer must be consumed exactly once and in the order placed into the buffer • Producer must not overwrite its own items and it should not leave any gaps
Shared variables • Use a count on number of items in the buffer • Producer increments when placing an item • Consumer decrements when removing item • Problem with updating shared variable (result can be unpredictable)
(producer) while (count>=n) wait place item in buffer count++ (consumer) while (count=0) wait remove an item from buffer count-- Updating count (common variable) Say count is 5 initially. After producer and consumer both execute, the result can be 4, 5 or 6 depending on relative execution of the two processes!
Producer code • Produce an item • while (in+1 mod n = out) wait; • buffer[in]=item produced; • item++ mod n
Consumer code • While (in=out) wait; • item=buffer[out] • out++ mod n; • consume removed item;
Updating shared variables • Can give any result and result not known and hard to debug.
Critical Sections • Mutual exclusion • No interference • No deadlock and starvation • No delay to enter if no process is in critical section • No assumption on relative process speeds • Process is critical section for a finite time only
Solutions to Critical Section • Hardware solutions • Software solutions
Semaphores • Is a synchronization tool • Integer variable whose value can be accessed through atomic operations wait and signal • Binary and counting semaphores • Implementations
Applications • Process synchronization (precedence constraints) using semaphores • Readers and writers problem • Bounded buffers problem • Other sutiations
Implementing precedence constraints using semaphores P3 can begin only after p1 terminates p1 p3 p2 p4
Code for p1 s12, s13: semaphore init 0; perform task associated with p1 signal(s12); signal(s13); Code for p2 s24:semaphore init 0; wait(s12); perform task associated with p2 signal(s24);