Producer Consumer Using Double Queues

Published February 22, 2012 by Ram Mohan Raja, posted by GameDev.net
Do you see issues with this article? Let us know.
Advertisement

  • Download source - 4.02 KB

    License: Zlib


    Introduction

    Producer consumer is an old computer science problem. Many solutions have been proposed to solve this problem. The general approach is using a common queue. A single queue to which the producer writes data to and the consumer reads data from. Avoiding race conditions is done by locking the queue so that when the producer is writing, the consumer is not reading and vice versa.

    The problem with this approach is that whenever the producer puts data to the queue, it has to acquire a lock. Similarly whenever the consumer gets data, it has to lock the queue. This solution is inadequate on systems where the producer generates data in excess of a hundred thousand updates per second. In my opinion, a hundred thousand locks on the queue in one second is a huge performance penalty.

    Background

    Once while going over this conundrum with my better half, I was introduced to the concept of double queuing. Something similar to the double buffering used in graphics applications to avoid flicker. As far as my research goes, I was not able to find a similar solution to the producer consumer problem. In case this is duplication, my apologies. I would be indebted if you can point me to the original work.

    Double Queuing

    The solution proposed is very simple and elegant. Instead of using a single queue, we use two queues. At a given time, one queue is designated write queue and the other, the read queue. This helps us to avoid locking the queue while reading and writing to it. The producer is free to fill the write queue and the consumer is free to empty the read queue.

    When the consumer is done reading the read queue, the producer is blocked briefly and the queues are switched. Now the old read queue becomes the new write queue and the old write queue becomes the new read queue. After switching, if there is no data in the new read queue, the consumer is blocked. When the producer gets more data, it unblocks the consumer.

    The Code

    This solution makes use of Events for synchronization between the consumer and the producer. The producer code looks like this:


    public void ProducerFunc()
    {
    int data = 0;

    for (int i = 0; i < 10000; i++)
    {
    data += 1;
    MessageHandler(data);
    Thread.Sleep(m_Random.Next(0, 2));
    }
    }

    private void MessageHandler(int data)
    {
    m_UnblockHandlerEvent.WaitOne();
    m_HandlerFinishedEvent.Reset();

    m_CurrentWriteQueue.Enqueue(data);
    m_ProducerData.WriteLine(data); // logging

    m_DataAvailableEvent.Set();
    m_HandlerFinishedEvent.Set();
    }




    The ProducerFunc() is a thread function that is invoked 10,000 times. Every time MessageHandler() is called, it checks to see if it has been blocked by the consumer. If not, it resets the ManualResetEvent to indicate to the consumer that the producer has not yet finished. This is useful when the consumer is trying to switch the queues and wants to know if the producer is finished writing to the queue. The rest of the code is straight forward. Data is written to queue and an event is set to wake up the consumer incase it was blocked. Finally, an event is set to indicate that the producer is finished writing to queue.

    This is the consumer code:


    public void ConsumerFunc()
    {
    int count;
    int data;
    Queue readQueue;

    while (true)
    {
    m_DataAvailableEvent.WaitOne();

    m_UnblockHandlerEvent.Reset(); // block the producer
    m_HandlerFinishedEvent.WaitOne(); // wait for the producer to finish
    readQueue = m_CurrentWriteQueue;
    // switch the write queue
    m_CurrentWriteQueue = (m_CurrentWriteQueue == m_Q1) ? m_Q2 : m_Q1;
    m_UnblockHandlerEvent.Set(); // unblock the producer

    count = ;
    while (readQueue.Count > )
    {
    count += 1;

    data = readQueue.Dequeue();
    m_ConsumerData.WriteLine(data); // logging

    Thread.Sleep(m_Random.Next(0, 2));
    }
    Console.WriteLine("Removed {0} items from queue: {1}",
    count, readQueue.GetHashCode());
    }
    }




    The ConsumerFunc() is a separate thread function. When the function starts, it checks to see if the data present event has been set. If not, then it is blocked till we get data written by the producer. Once data is present in the queue, the consumer resets the event to block the producer and waits for the producer to finish. The current write queue is now cached for reading and the current write queue is switched. After the queue is switched, the producer is unblocked to enable it to start writing to the new write queue. Meanwhile the consumer is busy reading from the read queue. Once the queue is empty, the entire process is repeated.

    Points of Interest

    On further discussing this solution with others, I was told using synchronization events causes more performance problems than using lock. What do you think about that argument? Can you shed some light on this from your experiences with lock and synchronization events?

    About the Author

    Nothing to brag about! Just another passionate software developer!

    Work to make a living, don't live to work!



    License

    This article was authored by Ram Mohan Raja and reproduced for the benefit of our viewers under the terms of the Zlib license.

Cancel Save
0 Likes 1 Comments

Comments

Nihat Tabak

Your website is very nice. I visit all the time. You been sharing useful information.
We are familiar with in your way.
How much do my very te?ekür the sulfur, the sulfur I do not know how to thank you. Thank you so much
Getting useful information for my website

Sesli Chat ne-nerede nenerede bonibon
speakychat sesliduy sesliduy sesliduy sesliduy seslichat seslichat seslichat sesli sohbet seslisohbet seslichat seslisayfam seslisayfam seslisayfam seslisayfam seslisayfam seslicevher seslisayfam seslicevher seslicevher sesli dunya seslidunya sesli dünya seslipop seslipop seslipop kral tv sesli 18 web tasarim video klip videoklip faceebook kürtce chatSchlüsselnotdienst Hamburg Schlüsseldienst Hamburg Schlüsseldienst Hamburg
April 08, 2016 01:32 AM
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Advertisement