Feb 14, 2011

Producer and Consumer Problem using Windows Threads

Above is class diagram for a simple producer/consumer problem
#include <iostream>
#include "MQ.h"
#include "Thread.h"
#include "Runnable.h"
#include "ProductionTask.h"
#include "ConsumptionTask.h"

//File: Main.cpp

using namespace examples;

int main()
{
    try
    {
        MQ q(10);
        ProductionTask producerTask(q);
        ConsumptionTask consumerTask(q);
        Thread t[2] = { producerTask, consumerTask };

        //start the producer and consumer threads
        t[0].start();
        t[1].start();

        //wait 50000 ms before terminating the threads
        t[0].join(50000);
        t[1].join(50000);
        std::cout << std::endl
            << "Threads timed out!!" << std::endl;

    }catch(std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }catch(...)
    {
        std::cerr << "Unknown Exception" << std::endl;
    }
    return 0;
}
Key Features

1. Threads are Tasks are decoupled. A thread can execute any task provided it implements the Runnable interface.
2. Windows threads are encapsulated using the technique demonstrated in the earlier blog post Encapsulating Windows Threads in C++ Objects
3. Two Tasks ProductionTask and ConsumptionTask share the common MQ instance q and try to execute add and remove operations on q concurrently. Synchronization is achieved here by means of Lock implemented using Windows CRITICAL_SECTION
4. The threads are allowed to run for 50 seconds before they are terminated. This is not a graceful termination and in real world applications may lead to unexpected results
#ifndef _Runnable_H_
#define _Runnable_H_

//File: Runnable.h

#include <iostream>
#include "NonCopyable.h"

namespace examples
{
    class Runnable
    {
    public:
        virtual ~Runnable(){}
        virtual void run() = 0;
    };

}

#endif //_Runnable_H_
#ifndef _ConsumptionTask_H_
#define _ConsumptionTask_H_

//File: ConsumptionTask.h

#include "Runnable.h"
#include "MQ.h"

namespace examples
{
    class ConsumptionTask : public Runnable
    {
    public:
        ConsumptionTask(MQ &q);
        ~ConsumptionTask();
        virtual void run();

    private:
        MQ&  m_queue;
    };

}

#endif //_ConsumptionTask_H_
#include "ConsumptionTask.h"

//File: ConsumptionTask.cpp

using namespace examples;

ConsumptionTask::ConsumptionTask(MQ &q) : m_queue(q)
{}

ConsumptionTask::~ConsumptionTask()
{}

void ConsumptionTask::run()
{
    while(true)
    {
        m_queue.remove();
        ::Sleep(550);
    }
}
#ifndef _ProductionTask_H_
#define _ProductionTask_H_

//File: ProductionTask.h

#include "Runnable.h"
#include "MQ.h"

namespace examples
{
    class ProductionTask : public Runnable
    {
    public:
        ProductionTask(MQ &q);
        ~ProductionTask();
        virtual void run();

    private:
        MQ&  m_queue;
    };

}

#endif //_ProductionTask_H_
#include "ProductionTask.h"

//File: ProductionTask.cpp

using namespace examples;

ProductionTask::ProductionTask(MQ &q) : m_queue(q)
{}

ProductionTask::~ProductionTask()
{}

void ProductionTask::run()
{
    while(true)
    {
        m_queue.add("Object");
        ::Sleep(500);
    }
}

#ifndef _Lock_H_
#define _Lock_H_

//File: Lock.h

#include <windows.h>
#include <process.h>
#include "NonCopyable.h"

namespace examples
{
    class Lock : public NonCopyable
    {
    public:
        Lock()
        {
            ::InitializeCriticalSection(&m_cs);
        }

        ~Lock()
        {
            ::DeleteCriticalSection(&m_cs);
        }

        void acquire()
        {
            ::EnterCriticalSection(&m_cs);
        }

        void release()
        {
            ::LeaveCriticalSection(&m_cs);
        }

    private:

        CRITICAL_SECTION m_cs;
    };

}

#endif //_Lock_H_
#ifndef _MQ_H_
#define _MQ_H_

//File: MQ.h

#include <iostream>
#include <deque>
#include "Lock.h"

using namespace std;


namespace examples
{
    class MQ
    {
    public:
        MQ(size_t SIZE = 10) : Q_MAX_SIZE(SIZE){}

        ~MQ()
        {
            m_q.clear();
        }

        void add(const string& elem)
        {
            m_lock.acquire();
            if(m_q.size() == Q_MAX_SIZE - 1)
            {
                std::cout << "Queue full" << std::endl;
                m_lock.release();
                ::Sleep(5000);
                return;
            }
            m_q.push_back(elem);
            debug_print();
            m_lock.release();
        }

        void remove()
        {
            m_lock.acquire();
            if(m_q.size() == 0)
            {
                std::cout << "Queue empty" << std::endl;
                m_lock.release();
                return;
            }
            m_q.pop_front();
            debug_print();
            m_lock.release();
        }

        void debug_print()
        {
            std::cout << "\r\b";
            std::cout << "Size=[" << m_q.size() << "]";
        }

    private:
        const size_t Q_MAX_SIZE;
        deque<const string>   m_q;
        Lock           m_lock;
    };

}

#endif //_MQ_H_
#ifndef _Thread_H_
#define _Thread_H_

//File: Thread.h

#include "NonCopyable.h"
#include "Runnable.h"

namespace examples
{
    class Thread : public NonCopyable
    {
    public:
        Thread(Runnable&);
        ~Thread();

        bool join();
        bool join(size_t ms);
        void start();
        void setName(const std::string&);
        const char* getName() const;

    private:
        Thread();

        class ThreadImpl *m_impl;
    };

}

#endif //_Thread_H_
#include "Thread.h"
#include "ThreadImpl.h"
#include <iostream>

//File: Thread.cpp

using namespace examples;

Thread::Thread(Runnable& task) : m_impl(new ThreadImpl(task))
{}

Thread::~Thread()
{}

bool Thread::join()
{
    return m_impl->join();
}

bool Thread::join(size_t ms)
{
    return m_impl->join(ms);
}

const char* Thread::getName() const
{
    return m_impl->getName();
}

void Thread::setName(const std::string& thrName)
{
    return m_impl->setName(thrName);
}

void Thread::start()
{
    m_impl->start();
}
#ifndef _ThreadImpl_H_
#define _ThreadImpl_H_

//File: ThreadImpl.h

#include <windows.h>
#include <process.h>
#include <iostream>
#include <string>
#include "NonCopyable.h"
#include "Runnable.h"

namespace examples
{
    class ThreadImpl : public NonCopyable
    {
    public:
        ThreadImpl(Runnable&);
        ThreadImpl(const std::string&, Runnable&);
        ~ThreadImpl();

        bool join() const;
        bool join(size_t) const;
        void start() const;
        void setName(const std::string&);
        const char* getName() const;

    private:
        ThreadImpl();

        static unsigned __stdcall dispatch(void *);
        bool spawn(Runnable&);

        HANDLE      m_hthread;
        unsigned    m_thrdid;
        std::string m_thrName;
    };

}

#endif //_ThreadImpl_H_
#include "ThreadImpl.h"
#include "Runnable.h"

//File: ThreadImpl.cpp

using namespace examples;

unsigned __stdcall ThreadImpl::dispatch(void *args)
{
    Runnable *task = static_cast<Runnable *>(args);
    task->run();
    return 0;
}

ThreadImpl::ThreadImpl(Runnable& task) : m_hthread(0), m_thrdid(0), m_thrName("")
{
    spawn(task);
}

ThreadImpl::ThreadImpl(const std::string& thrName, Runnable& task) : m_hthread(0), m_thrdid(0), m_thrName(thrName)
{
    spawn(task);
}

ThreadImpl::~ThreadImpl()
{
    ::CloseHandle(m_hthread);
    m_hthread = NULL;
}

const char* ThreadImpl::getName() const
{
    return m_thrName.c_str();
}

void ThreadImpl::setName(const std::string& thrName)
{
    m_thrName = thrName;
}

bool ThreadImpl::spawn(Runnable &task)
{
    m_hthread = (HANDLE) ::_beginthreadex(0, 0, &ThreadImpl::dispatch, &task, CREATE_SUSPENDED, &m_thrdid);
    return m_hthread != NULL;
}

bool ThreadImpl::join() const

{
    DWORD retval = ::WaitForSingleObjectEx(m_hthread, INFINITE, false);
    return retval == WAIT_OBJECT_0;
}

bool ThreadImpl::join(size_t ms) const
{
    DWORD retval = ::WaitForSingleObjectEx(m_hthread, ms, false);
    return retval == WAIT_OBJECT_0;
}

void ThreadImpl::start() const
{
    ::ResumeThread(m_hthread);
}

Sample Run of the Program:

64 comments:

  1. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
    Digital Marketing Training in Chennai

    Digital Marketing Training in Bangalore

    digital marketing training in tambaram

    digital marketing training in annanagar

    ReplyDelete
  2. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    full stack developer training in annanagar

    full stack developer training in tambaram

    full stack developer training in velachery

    ReplyDelete
  3. Thanks for such a great article here. I was searching for something like this for quite a long time and at last I’ve found it on your blog. It was definitely interesting for me to read  about their market situation nowadays.
    python training institute in chennai
    python training in Bangalore
    python training institute in chennai

    ReplyDelete
  4. A universal message I suppose, not giving up is the formula for success I think. Some things take longer than others to accomplish, so people must understand that they should have their eyes on the goal, and that should keep them motivated to see it out til the end.

    java training in jayanagar | java training in electronic city

    java training in chennai | java training in USA

    ReplyDelete
  5. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    python training in tambaram
    python training in annanagar
    python training in jayanagar

    ReplyDelete
  6. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
    Devops training in marathahalli
    Devops training in rajajinagar

    ReplyDelete
  7. I would like to thank you for your nicely written post, its informative and your writing style encouraged me to read it till end. Thanks
    Microsoft Azure online training
    Selenium online training
    Java online training
    Java Script online training
    Share Point online training

    ReplyDelete
  8. Thank you for this post!! I have just discovered your blog recently and I really like it! I will definitely try some of your insights.
    Regards,
    SQL Training in Chennai | SQL DPA Training in Chennai | SQL Training institute in Chennai

    ReplyDelete
  9. It has been simply incredibly generous with you to provide openly what exactly many individuals would’ve marketed for an eBook to end up making some cash for their end, primarily given that you could have tried it in the event you wanted.
    Data Science Training in Chennai | Data Science Course in Chennai
    Python Course in Chennai | Python Training Course Institutes in Chennai
    RPA Training in Chennai | RPA Training in Chennai
    Digital Marketing Course in Chennai | Best Digital Marketing Training in Chennai

    ReplyDelete
  10. You might comment on the order system of the blog. You should chat it's splendid. Your blog audit would swell up your visitors. I was very pleased to find this site.I wanted to thank you for this great read!!
    www.excelr.com/digital-marketing-training
    digital marketing course

    ReplyDelete
  11. Attend The Python Training in Bangalore From ExcelR. Practical Python Training in Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python Training in Bangalore.

    ReplyDelete
  12. Wow, what an awesome spot to spend hours and hours! It's beautiful and I'm also surprised that you had it all to yourselves! Kindly visit us @ Best HIV Treatment in India | Top HIV Hospital in India | HIV AIDS Treatment in Mumbai
    HIV Specialist in Bangalore | HIV Positive Treatment in India | Medicine for AIDS in India

    ReplyDelete
  13. I like your post very much. It is very much useful for my research. I hope you to share more info about this. Keep posting!!


    Best Devops Training Institute

    ReplyDelete
  14. Tableau course in Hyderabad from ExcelR,Here we provide training from experts

    ReplyDelete
  15. Nice Post! Thank you for sharing very good post, it was so Nice to read and useful to improve my knowledge as updated one, keep blogging!! Machine Learning Course

    ReplyDelete
  16. This comment has been removed by the author.

    ReplyDelete
  17. This comment has been removed by the author.

    ReplyDelete
  18. thank you for sharing this blog, it is useful for understanding the producer and consumer problem.
    AWS training bangalore

    ReplyDelete
  19. very good blog really useful to me...

    https://www.acte.in/angular-js-training-in-chennai
    https://www.acte.in/angular-js-training-in-annanagar
    https://www.acte.in/angular-js-training-in-omr
    https://www.acte.in/angular-js-training-in-porur
    https://www.acte.in/angular-js-training-in-tambaram
    https://www.acte.in/angular-js-training-in-velachery

    ReplyDelete
  20. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging…
    AWS training in chennai | AWS training in anna nagar | AWS training in omr | AWS training in porur | AWS training in tambaram | AWS training in velachery

    ReplyDelete
  21. The site was so nice, I found out about a lot of great things. I like the way you make your blog posts. Keep up the good work and may you gain success in the long run.

    Big Data Hadoop Training In Chennai | Big Data Hadoop Training In anna nagar | Big Data Hadoop Training In omr | Big Data Hadoop Training In porur | Big Data Hadoop Training In tambaram | Big Data Hadoop Training In velachery


    ReplyDelete
  22. 360DigiTMG, a data science institute in indore, is a leading solutions provider of Training and Consulting to assist students, professionals by delivering top-notch, world-class classroom and online training.


    ReplyDelete
  23. Yes, the post is very interesting and I really like it. I never seen articles like this. I meant it's so knowledge, informative, and good looking site. I appreciate your hard work and share any more information.
    thank you.
    python training in chennai

    python online training in chennai

    python training in bangalore

    python training in hyderabad

    python online training

    python flask training

    python flask online training

    python training in coimbatore

    ReplyDelete
  24. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
    data science using python and r programming coimbatore

    ReplyDelete
  25. If you want them to take your application from good to great, hiring them for app development project will be the best option. It is amazing and wonderful to visit your site.
    oracle training in chennai

    oracle training in tambaram

    oracle dba training in chennai

    oracle dba training in tambaram

    ccna training in chennai

    ccna training in tambaram

    seo training in chennai

    seo training in tambaram

    ReplyDelete
  26. I read your blog occasionally, and I own a similar one, and I was just wondering if you get a lot of spam remarks? If so how do you stop it, any plugin or anything you can advise? I get so much lately it’s driving me insane, so any assistance is very much appreciated.
    IELTS Coaching in chennai

    German Classes in Chennai

    GRE Coaching Classes in Chennai

    TOEFL Coaching in Chennai

    Spoken english classes in chennai | Communication training

    ReplyDelete
  27. Awesome blog. It was very informative. I would like to appreciate you. Keep updated like this!
    Python Training in Gurgaon

    ReplyDelete
  28. It was really nice blog with lot of innovative thing inside this,I really enjoyable i would like to thank for sharing this valuable content.I was so glad to see this wonerful blog.keep updating your blog.
    amazon web services aws training in chennai

    microsoft azure training in chennai

    workday training in chennai

    android-training-in chennai

    ios training in chennai

    ReplyDelete
  29. This is the exact information I am been searching for, Thanks for sharing the required infos with the clear update and required points.
    amazon web services aws training in chennai

    microsoft azure training in chennai

    workday training in chennai

    android-training-in chennai

    ios training in chennai

    ReplyDelete
  30. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet
    effective. A lot of times it’s very hard to get that “perfect balance”
    between superb usability and visual appeal. I must say you’ve done a
    very good job with this.
    dot net course in chennai
    core java training classes in chennai
    manual testing training in chennai

    ReplyDelete
  31. Much thanks to you for taking the length to talk about this, I have a firm opinion roughly it and commend getting to know additional going vis- - vis for this issue. On the off chance that feasible, as you benefit speed, could you considerations refreshing your weblog long past helper assessment? it's miles the total obliging for me. Bandicam Key Generator

    ReplyDelete
  32. Took me term to entryway all the explanation, but I in all actuality partook in the article. It ended up being Very respecting me not entirely set in stone to all the analysts here! Its generally accessible by means of now you can't unmarried-handedly be learned, however with engaged! Mega Crack

    ReplyDelete
  33. Love failure quotes are for the one who failed in love. Love failure makes you realize the best moments you have lived or are living with.Quotes On Love Failure

    ReplyDelete
  34. Actually, I visited your blog. It's lovely, so keep writing.I appreciate you sharing...

    ReplyDelete

  35. Best institute in Hyderabad is Data Science School i really love your contain

    https://datascienceschool.in/

    ReplyDelete
  36. I was looking for this kind of information and enjoyed reading this one. Azure Data Engineering Training in Hyderabad

    ReplyDelete