08.07.2015 Views

Topic Notes: Process Synchronization - Courses

Topic Notes: Process Synchronization - Courses

Topic Notes: Process Synchronization - Courses

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CS 322 Operating Systems Spring 2008See Example:/cluster/examples/prodcons-shmemSee Example:/cluster/examples/prodcons-pthreadsIs there any danger with this solution in terms of concurrency? Remember that these processescan be interleaved in any order – the system could preempt the producer at any time and run theconsumer.. Things to be careful about are shared references to variables.Note that only one of the processes can modify the variables in and out. Both use the values,but only the producer modifies in and only the consumer modifies out. Try to come up with asituation that causes incorrect behavior – hopefully you cannot.Perhaps we want to use the entire buffer...let’s add a variable to keep track of how many items arein the buffer, so we can tell the difference between an empty and a full buffer:• Shared dataint buffer[n];int in=0;int out=0;int counter=0;• Producer processwhile (1) {...produce item;...while (counter==n); /* busy wait */buffer[in]=item;in=(in+1)%n;counter=counter+1;}• Consumer processwhile (1) {while (counter==0); /* busy wait */item=buffer[out];out=(out+1)%n;counter=counter-1;...consume item;...}3

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!