Posted by : Sushanth Tuesday, 15 December 2015

Producer/Consumer Problem:
Producers create items of some kind and add them to a data structure; consumers
remove the items and process them.
Example: Event-driven programs are a good example. An “event” is something that happens that requires the program to respond: the user presses a key or moves the mouse, a block of data arrives from the disk, a packet arrives from the network, a pending operation completes.
Whenever an event occurs, a producer thread creates an event object and adds it to the event buffer. Concurrently, consumer threads take events out of the buffer and process them. In this case, the consumers are called “event handlers.”

Producer-consumer with infinite buffer:
Basic Producer Code:
event = waitForEvent()
 buffer.add(event)
Basic consumer code:
            event = buffer.get()
 event.process()

Producer-consumer initialization:
1 mutex = Semaphore(1)
2 items = Semaphore(0)
3 local event

Producer solution:
1 event = waitForEvent()
2 mutex.wait()
3 buffer.add(event)
4 mutex.signal()
5 items.signal()

Consumer solution:
1 items.wait()
2 mutex.wait()
3 event = buffer.get()
4 mutex.signal()
5 event.process()




Producer-consumer with a finite buffer:
Initialization:
1 mutex = Semaphore(1)
2 items = Semaphore(0)
3 spaces = Semaphore(buffer.size())
consumer solution
1 items.wait()
2 mutex.wait()
3 event = buffer.get()
4 mutex.signal()
5 spaces.signal()
6 event.process()
producer solution:
1 event = waitForEvent()
2
3 spaces.wait()
4 mutex.wait()
5 buffer.add(event)
6 mutex.signal()
7 items.signal()


Leave a Reply

Subscribe to Posts | Subscribe to Comments

- Copyright © Technical Articles - Skyblue - Powered by Blogger - Designed by Johanes Djogan -