A Developer's Diary

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:

60 comments :

gowsalya said...

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

Anonymous said...

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

nilashri said...

Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
Data Science training in btm
Data Science training in rajaji nagar
Data Science training in chennai
Data Science training in kalyan nagar
Data Science training in electronic city
Data Science training in USA
selenium training in chennai
selenium training in bangalore

Mounika said...

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

Unknown said...

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

JAHAN said...

Hello. This post couldn’t be written any better! Reading this post reminds me of my previous roommate. He always kept chatting about this. I will forward this page to him. Fairly certain he will have a good read. Thank you for sharing.


AWS Training in Bangalore | Amazon Web Services Training in Bangalore

Amazon Web Services Training in Pune | Best AWS Training in Pune

AWS Online Training | Online AWS Certification Course - Gangboard

Selenium Training in Chennai | Best Selenium Training in Chennai

Selenium Training in Bangalore | Best Selenium Training in Bangalore


saimouni said...

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

gowsalya said...

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

genga g said...

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic.
angularjs interview questions and answers

angularjs Training in bangalore

angularjs Training in bangalore

angularjs online Training

angularjs Training in marathahalli

Sherin Alfonsa said...

I am eagerly waiting for your next blog!!! keep updating more contents.

Selenium Training in Chennai
selenium Classes in chennai
iOS Training in Chennai
French Classes in Chennai
Big Data Training in Chennai
Digital Marketing Training in Chennai
Digital Marketing Training

jefrin said...

Thanks for posting this blog very useful
SQL DBA training in chennai

haripriya said...

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

kamal said...

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

user123 said...

Hey, would you mind if I share your blog with my twitter group? There’s a lot of folks that I think would enjoy your content. Please let me know. Thank you.
AWS Training in Chennai | Best AWS Training in Chennai | AWS Training Course in Chennai
Data Science Training in Chennai | Best Data Science Training in Chennai | Data Science Course in Chennai
No.1 Python Training in Chennai | Best Python Training in Chennai | Python Course in Chennai
RPA Course Training in Chennai | Best RPA Training in Chennai
No.1 RPA Training in Chennai | Best RPA Training in Chennai | RPA Course in Chennai
No.1 Digital Marketing Training in Chennai | Best Digital Marketing Training in Chennai

jvimala said...

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

Karthick Ganesan said...

And indeed, I’m just always astounded concerning the remarkable things served by you. Some four facts on this page are undeniably the most effective I’ve had.
Java Training in Chennai |Best Java Training course in Chennai
C C++ Training in Chennai |Best C C++ Training course in Chennai
Python Training in Chennai| Python Training institute in Chennai
Datascience Training in Chennai |Datascience Training institute in Chennai
RPA Training in Chennai | RPA Training institute in Chennai
MCSA / MCSE TRAINING IN CHENNAI |Best MCSE TRAINING course IN CHENNAI
CCNA TRAINING IN CHENNAI | Best CCNA TRAINING course IN CHENNAI
ANDROID TRAINING IN CHENNAI |Best ANDROID TRAINING course IN CHENNAI

Rathinam said...

Superb post!!! I love this post and thanks for your wrathful post. I expected the next posts and keep posting...
Oracle Training in Chennai
Oracle Training institute in chennai
Tableau Training in Chennai
Spark Training in Chennai
Unix Training in Chennai
Power BI Training in Chennai
Oracle DBA Training in Chennai
Oracle Training in Chennai
Oracle Training institute in chennai

digitaltucr said...

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

Priyanka said...

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.

Malaivel Siddha Hospital said...

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

KIT said...

Nice blog, it's so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job. Thank you for this wonderful sharing with us. Keep Sharing. Kindly visit us @ 100% Job Placement | Best Colleges for Computer Engineering
Biomedical Engineering Colleges in Coimbatore | Best Biotechnology Colleges in Tamilnadu | Biotechnology Colleges in Coimbatore
Biotechnology Courses in Coimbatore | Best MCA Colleges in Tamilnadu | Best MBA Colleges in Coimbatore
Engineering Courses in Tamilnadu | Engg Colleges in Coimbatore

anirudh said...

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

vamsi said...

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

ExcelR Solutions said...

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

KIT said...


A very inspiring blog your article is so convincing that I never stop myself to say something about it.

Prwatech said...
This comment has been removed by the author.
Vijiaajith said...

Nice content
freeinplanttrainingcourseforECEstudents
internship-in-chennai-for-bsc
inplant-training-for-automobile-engineering-students
freeinplanttrainingfor-ECEstudents-in-chennai
internship-for-cse-students-in-bsnl
application-for-industrial-training

preethi minion said...

nice
inplant training in chennai
inplant training in chennai
inplant training in chennai for it.php
italy web hosting
afghanistan hosting
angola hosting
afghanistan web hosting
bahrain web hosting
belize web hosting
india shared web hosting

kani said...

nice..
hosting
india hosting
india web hosting
iran web hosting
technology 11 great image sites like imgur hosting
final year project dotnet server hacking what is web hosting
macao web hosting
inplant training in chennai
inplant training in chennai
inplant training in chennai for it.php

Anand Shankar said...
This comment has been removed by the author.
Trishana said...

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

i Digital Academy said...

Thanks for sharing such a nice blog with us...
Digital Marketing Training in Bangalore

Shanthi Cabs said...

Nice blog...
Best Travels in Madurai | Tours and Travels in Madurai | Best tour operators in Madurai

nizam said...

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

Rashika said...

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

Madhuvarsha said...

Interesting information and an awesome post.

AngularJS training in chennai | AngularJS training in anna nagar | AngularJS training in omr | AngularJS training in porur | AngularJS training in tambaram | AngularJS training in velachery



Anonymous said...

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


Keerthi said...

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.


rocky said...

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

360digitmgas said...

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

shankarjaya said...

Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.
Salesforce Training in Chennai

Salesforce Online Training in Chennai

Salesforce Training in Bangalore

Salesforce Training in Hyderabad

Salesforce training in ameerpet

Salesforce Training in Pune

Salesforce Online Training

Salesforce Training

Jayalakshmi said...

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

praveen said...

First i got a great blog .I will be interested in more similar topics. i see you got really very useful topics, i will be always checking your blog thanks.
hadoop training in chennai

hadoop training in porur

salesforce training in chennai

salesforce training in porur

c and c plus plus course in chennai

c and c plus plus course in porur

machine learning training in chennai

machine learning training in porur

deiva said...

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.
java training in chennai

java training in omr

aws training in chennai

aws training in omr

python training in chennai

python training in omr

selenium training in chennai

selenium training in omr

ganesh said...

This is the exact information I am been searching for, Thanks for sharing the required infos with the clear update and required points.

Angular js Training in Chennai

Angular js Training in Velachery

Angular js Training in Tambaram

Angular js Training in Porur

Angular js Training in Omr

Angular js Training in Annanagar


Pushba said...

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

Amrita Bansal said...

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

ramya said...

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

ramya said...

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

David Fincher said...

This post is so interactive and informative.keep update more information...
Spoken English Classes in Tambaram
Spoken English Classes in Chennai

Block said...

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

French language classes in Chennai said...

Thanks for the blog, Its good and valuable information.
Japanese Language Course | Japanese Classes Near Me

Anonymous said...

en son çıkan perde modelleri
SMS ONAY
MOBİL ÖDEME BOZDURMA
nftnasilalinir
ANKARA EVDEN EVE NAKLÄ°YAT
trafik sigortası
DEDEKTOR
Web sitesi kurma
AÅžK ROMANLARI

Anonymous said...

smm panel
Smm Panel
iş ilanları
instagram takipçi satın al
hirdavatciburada.com
beyazesyateknikservisi.com.tr
Servis
TÄ°KTOK JETON HÄ°LESÄ° Ä°NDÄ°R

Hi Every One said...

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

Cyberz Pc said...

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

syedhaseeb said...

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

saikumar0801 said...

This is nice and more informative, Thank you for sharing it!

Python Training in Hyderabad with Placements

vcube said...

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

vv software said...

I love your Blog. Keep up the fantastic work!
Python Course training institute in hyd

Post a Comment