p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/)
-   BOOK Programming Interviews Exposed: Secrets to Landing Your Next Job 3rd Edition (http://p2p.wrox.com/book-programming-interviews-exposed-secrets-landing-your-next-job-3rd-edition-704/)
-   -   questions on Producer Consumer (http://p2p.wrox.com/book-programming-interviews-exposed-secrets-landing-your-next-job-3rd-edition/92366-questions-producer-consumer.html)

flethuseo March 6th, 2014 02:42 AM

questions on Producer Consumer
Hi all,

1. In the code for the producer/consumer without any synchronization, why is there a 'while true' in the add and remove methods? I have removed it and it seems to work better:

                private void add(int num) {
                        if (index < buffer.length) {
                                buffer[index++] = num;

                private int remove() {
                        if (index > 0) {
                                return buffer[--index];
                        return -1;

2. After synchronizing access to the buffer for the producer and consumer. What would be the best way to make the consumer stop when the producer stops producing and the queue is empty?

John Mongan July 11th, 2017 04:18 PM

Without the while loops, add will silently fail to add the value to the buffer if it is full, and remove will fail to retrieve a valid value from the queue if it is empty.

There are a variety of means that can be used to stop the consumer. One way to do it is called "poison pill": when the producer is ready to shut down it puts a special value on the queue just before it shuts down; when the consumer sees that value it shuts down. To make this work, you have to be sure that the special "poison pill" value is one that would never be placed on the queue in any other context, or you'll have the consumer shutting down when you don't want it to.


ynaija July 20th, 2017 08:32 AM

Where to check Nigeriens day today updated news?
You can check the Latest news in Nigeria only from YNaija because ynaija is the internet newspaper for young Nigerians, focused on the issues and ideas that matter for an evolving generation.

All times are GMT -4. The time now is 07:42 PM.

Powered by vBulletin®
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
2013 John Wiley & Sons, Inc.