# CA-2019Fall: Quiz 5 ## `A` In lecture about Synchronization, you saw the use of semaphores to mediate a communication stream between a Producer and a Consumer process. In this problem, we assume the existence of three asynchronous processes: a Producer process, producing a stream of characters; a Consumer process, which consumes a stream of characters; and a Filter process spliced between the Consumer and Producer processes. The Filter process takes characters from the producer, processes them (via a `translate` function), and passes the result to the Consumer process. The Producer and Consumer processes each communicate directly only with the Filter process. The following is in Shared Memory (shared among Producer, Filter, and Consumer processes): ```cpp Semaphore charsA = ???, spaceA = ???, charsB = ???, spaceB = ???; char buf[100]; char indata; int in = 0, out = 0; ``` and the following code runs in the Filter Process: ```cpp while (1) { char temp; /* local variable */ wait(charsA); temp = indata; signal(spaceA); temp = translate(temp); /* do the actual translation */ wait(spaceB); buf[in] = temp; in = (in + 1) % 100; /* increment ‘in’ modulo 100 */ signal(charsB); } ``` What are appropriate initial values for each of the semaphores? * initial value for charsA: ________________ * initial value for spaceA: ________________ * initial value for charsB: ________________ * initial value for spaceB: ________________ ## `B`: extending `A` For each of the following lines of code, indicate whether you would expect to find them in the Producer process (==`P`==), the Consumer process (==`C`==), or Neither process (==`N`==): * `out = (out + 1) % 100;` in process ________ * `signal(charsA);` in process ________ * `signal(indata);` in process ________ * `wait(charsB);` in process ________ :::info :notes: Fill `P`, `C`, or `N` in each item. ::: ## `C`: extending `B` Assuming that the only process synchronization appearing in the Producer and Consumer processes is the use of the four semaphores shown, will the above implementation work with multiple Consumer processes? Multiple Producer processes? Multiple Filter processes? "Work" means each character produced by a Producer is translated by exactly one Filter process and then consumed by exactly one Consumer process, i.e., no character is lost or processed twice. * Works with multiple Consumers: ________ * Works with multiple Producers: ________ * Works with multiple Filters: ________ :::info :notes: Fill `Yes` or `No` in each item. ::: --- ## Answer ### A * initial value for charsA: 0 * initial value for spaceA: 1 * initial value for charsB: 0 * initial value for spaceB: 100 ### B * out = (out + 1) % 100; in process C * signal(charsA); in process P * signal(indata); in process N * wait(charsB); in process C ### C * Works with multiple Consumers: No * Works with multiple Producers: Yes * Works with multiple Filters: No