The Open Source Swiss Army Knife

/code/c/unix_c/
/code/c/unix_c/ + sub-categories
http://www.sirfsup.com/
web directory content
    
      

Not logged in
Chat Register Login
return to:  http:/www.sirfsup.com      /code   /c   /unix_c 
Permalink: ipc.txt
Title: add
article options : please login   |  raw source view  

process synchronization


read sgz book chapter 7
process synchronization: getting processes to work together in a coordinated way.
producer/consumer problem: also called the bounded buffer problem because the buffer has only so many slots. Producer and consumer need take items from one common buffer

consumer: consumes data; removes things; needs to keep track of where take next item from
producer: creates things; puts things in the array but can be thought of as happening concurrently; producer: where put next item

assume: a shared circular buffer of size n (is this a FIFO?) can wrap around to beginning of a buffer after consumer reaches end of the buffer (like a linked list).

reentrant functions? not really, nothing is used when it shouldn't be used. in and out are unique to producer and consumer respectively.

What can go wrong?
if the consumer is not as fast as the producer so the buffer fills up and writes over the things which were in the buffer.
Or, the opposite, where consumer takes out something which is not there.
Consumer: any free buffer slots? Consumer: really something in buffer?

The solution uses separate processes for consumer or producer. Can think of them as separate threads as they need to share the buffer.

pseducode

in indexes the next entry for insertion
out indexes the next entry for removal
count the global total number stored in buffer

producer loop:

        produce an item in nextp
        while (count == n) 
        buffer[in] = nextp;
        in = (in +1)%n;  // takes into account wrapping around to beginning
        count += 1;

consumer loop:

        while (count == 0) // nothing in buffer
                wait;
        nextc = buffer[out];
        out = (out + 1)%n;
        count--;
        consume item nextc;

manipulating in and out are not the problem because there are only one parameter.
Trick with the problem is that on the assembly level the count-- and count++ are not atomic so the registers will be different. it is 3 assembly language. Scheduler makes things run on assembly language.

suppose count++ is implemented as the following instructions:
r1 = count
r1 = r1 + 1
count = r1

(r1 is a register)

suppose count = 5

producer produces
consumer produces
and the producer loses the cpu after the instruction a

count = 5?????


Leave a Reply
Your Name:     anonymous
Your Email:
Website:  
Comments:

The author will be notified of your reply.
return to top