Showing posts with label Multi-threading. Show all posts
Showing posts with label Multi-threading. Show all posts

Sunday, February 7, 2010

Producer consumer

A common programing problem is program while writing performant client-server applications is to have multiple threads service client requests and data. This increases the effeftive throughput, expecially if the processing requires I/O to/from a slow device. With such a scenarion, having multiple threads to service client requests dramatically improves the thruput because if a thread is blocked for i/o, other threads can start processing on other requests.

In this blog, I present the code for a simple queuing mechanism.

First, we define some utility classes.

Locker is a convenient class to automatically lock and unlock a mutex. It is designed for exception safety. We lock the mutex in the constructor and unlock in the destructor.

The next class is a convenient class to start, stop and join threads. Note, that this class is a simple wrapper and it is not well designed for portabality. In the implementation here, we assume that we are using POSIX threads and all threads are daemon threads (daemon threads terminate when the app terminates as opposed to joinable threads, which have to terminate before the app is terminated by the OS.

Subclasses of this class must override the ThdFunc, which is the main thread function.

Note that there is a race condition in this arrangement. If we create the underlying pthread in the constructor itself, sometimes the ThdFunc gets called even before the constructor of MyThreadBase has finished ! Since the ThdFunc is a pure virtual function, we get a system "Null pointer exception! Therefore, the underlying thread is created in the start call, which can only be made when the constructor returns and the object is fully constructed by that time.


class MyThreadBase
{
protected:
    static void *startFunc(void *);

    pthread_t  m_thread;
    bool m_KeepRunning;
    bool m_isDaemon;

public:

    MyThreadBase(bool isDaemon = true );


    virtual ~MyThreadBase();

    void start();

    void kill();
    void join();

    virtual void ThdFunc() = 0;

    bool KeepRunning() {return m_KeepRunning; }
    void SetTerminateFlag() { m_KeepRunning = false;}
};

Here is the code in its entirety

#include <iostream>
#include <list>
#include <pthread.h>


using namespace std;

// Convenient class to make sure the
// mutex is unlocked even if there is 
// an exception.
struct Locker
{

    Locker(pthread_mutex_t & inMutex)
    : m_Mutex(inMutex)
    {
        ::pthread_mutex_lock( &m_Mutex);
    }

    ~Locker()
    {
        ::pthread_mutex_unlock( &m_Mutex );
    }

private:
    pthread_mutex_t & m_Mutex;
};



// This is the bonded-queue class. In the 
// example we use a list to store elements
// because we can remove items from the 
// front of the queue. We could have used a
// dqueue also. We did not want to use a vector
// because removing an item from the front of
// the vector will force a copy of all subsequent
// items in the vector. However, if you were using
// pointers to messages, then a vector would be
// more efficiend. Ideally, this class should
// be a template class and the data type should
// be a vector of shared_ptr

#define QUEUE_SIZE  10

class BQueue
{
    list m_Items;
    pthread_mutex_t  m_QueueMutex;
    pthread_cond_t   m_EmptyCond;   // wait on this while trying to read
    pthread_cond_t   m_FullCond;  // wait on this while trying to write
public:

    BQueue();
    ~BQueue();
    void  AddItem(int inItem);
    int   RemoveItem();
};

BQueue::BQueue()
{
    //m_Items.resize( QUEUE_SIZE );
    ::pthread_mutex_init( &m_QueueMutex, NULL );
    ::pthread_cond_init( &m_EmptyCond, NULL );
    ::pthread_cond_init( &m_FullCond, NULL );
}

BQueue::~BQueue()
{
}


int BQueue::RemoveItem()
{
    Locker w(m_QueueMutex);
    while( m_Items.empty() )
    {
        ::pthread_cond_wait( &m_EmptyCond, &m_QueueMutex );
    }
    int aRet = m_Items.front();
    m_Items.pop_front();
    ::pthread_cond_signal( &m_FullCond );
    return aRet;
}


void BQueue::AddItem(int inValue)
{
    Locker w( m_QueueMutex );
    while( m_Items.size() >= QUEUE_SIZE )
    {
        cout << "BQueue::AddItem, queue is full!\n";
        ::pthread_cond_wait( &m_FullCond, &m_QueueMutex);
    }

    m_Items.push_back( inValue );
    ::pthread_cond_signal( &m_EmptyCond );
}





class MyThreadBase
{
protected:
    static void *startFunc(void *);

    pthread_t  m_thread;
    bool m_KeepRunning;
    bool m_isDaemon;

public:

    MyThreadBase(bool isDaemon = true )
    : m_thread(0),
    m_KeepRunning(true),
    m_isDaemon( isDaemon )
    {
    }


    virtual ~MyThreadBase()
    {
    }

    void start()
    {
        // assert( m_thread == NULL );
        // This code is not exception safe.
        // We will have a memory leak if we
        // do not call pthread_attr_destroy

        ::pthread_attr_t attr;
        ::pthread_attr_init( &attr );
        ::pthread_attr_setdetachstate( &attr, m_isDaemon );
        ::pthread_create( &m_thread, &attr, startFunc, this );
        ::pthread_attr_destroy( &attr );
    }

    void kill()
    {
        m_KeepRunning = false;
        ::pthread_cancel( m_thread );
    }

    void join()
    {
        m_KeepRunning = false;
        ::pthread_join( m_thread, NULL );
    }

    virtual void ThdFunc() = 0;

    bool KeepRunning() {return m_KeepRunning; }
    void SetTerminateFlag() { m_KeepRunning = false;}
};

void * MyThreadBase::startFunc(void *p)
{
    MyThreadBase* ap( static_cast(p));
    try
    {
        ap->ThdFunc();
    }
    catch(...)
    {
        cout << "Exception caught in startFunc\n";
    }
    return NULL;
}

// Consumer threads pull off requests from
// the queue and process them.
class ConsumerThread: public MyThreadBase
{
    BQueue & m_Queue;

public:
    ConsumerThread(BQueue & inQ):MyThreadBase(true), m_Queue(inQ)
    {
    }

    ~ConsumerThread()
    {
    }

    void ThdFunc()
    {
        cout << "Hello, I am a consumer thread!\n";
        while( KeepRunning() )
        {
            int aData = m_Queue.RemoveItem();
            cout << "Data item is " << aData << "\n";
        }

    }

};

// Producer threads produce data and put into
// the queue.
class ProducerThread: public MyThreadBase
{

    bool m_Done;
    BQueue & m_Queue;

public:
    ProducerThread(BQueue & inQ ):
    MyThreadBase(true), m_Done(false), m_Queue(inQ)
    {
    }

    ~ProducerThread()
    {
    }

    bool done() {return m_Done ;}

    void ThdFunc()
    {
        for(int i=0; i< 100; i++)
        {
            cout << "Producer Thread: Adding item " << i << "\n";
            m_Queue.AddItem(  i );
        }
        m_Done = true;

    }

};


#define MAX_CONSUMERS 5
#define MAX_PRODUCERS 1


int main(int, char **)
{
    cout << "Hello world!\n";
    cout << "Bonded queue simulation. Please enter the following data...\n";


    BQueue a_Queue;

    ConsumerThread * ct[ MAX_CONSUMERS ];

    for(int i=0;i< MAX_CONSUMERS ;i++)
    {
        ct[i] = new ConsumerThread( a_Queue );
        ct[i]->start();
    }
    cout << "Consumer threads created!!\n";

    ProducerThread aProducer( a_Queue );
    aProducer.start();
    while(! aProducer.done() )
    {
        cout << "Main thread. Producer is not yet done!\n";
        ::sleep(10);
    }

    cout << "deleting all the threads...\n";

    for(int i=0;i< MAX_CONSUMERS ;i++)
    {
        ct[i]->kill();
        delete ct[i] ;
    }

}

Sunday, July 26, 2009

Barber Problem Solution in C++

The barber shop simulation is a good problem to practice multi-threading concepts. Here is the problem, which we need to simulate. Barber shop consists of a waiting room with 'n' chairs, and a barber room with one barber chair

  1. If there are no customers to be served the barber goes to sleep.
  2. If a customer enters the barber shop and all the chairs are occupied then customer leaves shop.
  3. If barber is busy but chairs are available then customer sits in one of the free chairs.
  4. If barber is asleep the customer wakes up barber.

Here is one solution to the barber problem using Windows threading primitives. Essential classes that we need:

  • Barber This class runs in a different thread. It calls BarberShop.GetNextCustomer to get an available customer.
  • Customer
  • BarberShop This is where all the business logic resides. The two main routines are GetNextCustomer, which picks up the next available customer from the queue or blocks on m_BarberSleepEvt if no customers. The NeedsHaircut routine adds a customer to the end of the queue of waiting customers if the queue has empty spaces. If not, it simply ignores the request. If the queue was empty before adding, then it means that the barber thread was waiting on the event and it releases the event after adding the customer.
  • Thread This is a utility class that can be used to start/stop threads. Simply derive your class from this class after overriding the virtual run method and then call the Start routine.

The entire solution is in 2 files. I compiled the code using Borland's command line C++ compiler (free).


File: BarberShopSimulation.h

#ifndef _BARBER_SHOP_SIMULATION_H
#define _BARBER_SHOP_SIMULATION_H


#define NUM_WAITING_CHAIRS  5


class Barber;
class Customer;
class BarberShop;

class Thread
{
    HANDLE m_ThreadHandle;
    bool m_Terminate;
    DWORD m_ThreadID;

    static DWORD _ThreadProc(void *);
public:
    Thread();
    virtual ~Thread();
    void Start();
    void Stop() {m_Terminate = true;}
    bool KeepRunning() {return !m_Terminate;}
    DWORD GetThreadID() const {return m_ThreadID;}
    virtual DWORD run() = 0;
};


class Barber : public Thread
{
    BarberShop & m_Shop;

public:
    Barber( BarberShop & inShop);
    ~Barber();
    DWORD run();
};


// Dummy class
class Customer
{
    int m_ID;
public:
    Customer(int inID) : m_ID(inID)
    {
    }
    int GetID() const  {return m_ID;}

    Customer(const Customer & inCust): m_ID( inCust.m_ID )
    {
    }
};


std::ostream & operator << (std::ostream & os, const Customer & inCust)
{
    os << inCust.GetID() ;
    return os;
}


class BarberShop
{

    std::auto_ptr m_Barber;
    HANDLE m_BarberSleepEvt;
    HANDLE m_Mutex;
    int m_Head, m_Tail;
    std::auto_ptr  m_WaitingCustomers[ NUM_WAITING_CHAIRS];

    inline incr(int& inValue)
    {
        ++inValue;
        if(inValue >= NUM_WAITING_CHAIRS )
            inValue = 0;
    }
public:
    BarberShop();
    ~BarberShop() {}

    void GetNextCusomer( std::auto_ptr & outCust);
    void NeedsHaircut( std::auto_ptr& inCust);
};



#endif // _BARBER_SHOP_SIMULATION_H

BarberShopSimulation.cpp

#include <iostream>
#include <windows.h>
#include "BarberShopSimulation.h"

// For random sleep
#include <stdio.h>javascript:void(0)
#include <stdlib.h>
#include <time.h>

// =================================================
//      Thread
// =================================================
Thread::Thread()
: m_ThreadHandle(NULL), m_Terminate(false)
{
}

Thread::~Thread()
{
    if( m_ThreadHandle != NULL )
    {
        ::TerminateThread( m_ThreadHandle, 0 );
        m_ThreadHandle = NULL;
    }
}

DWORD Thread::_ThreadProc(void *ap)
{
    Thread *r = (Thread *)ap;
    return r->run();
}

void Thread::Start()
{
    m_ThreadHandle = ::CreateThread(
                     NULL,       // default security attributes
                     0,          // default stack size
                     (LPTHREAD_START_ROUTINE) _ThreadProc,
                     this,       // no thread function arguments
                     0,          // default creation flags
                     &m_ThreadID); // receive thread identifier
    if( m_ThreadHandle == NULL )
        std::cout << "Could not create a thread!\n";
}

// =================================================
//      Barber
// =================================================
Barber:: Barber( BarberShop & inShop)
: m_Shop(inShop)
{
}
Barber::~Barber()
{
}

DWORD Barber::run()
{
    std::cout << "Barber::run...";
    while(1)
    {

        std::auto_ptr aCust;
        m_Shop.GetNextCusomer( aCust );
        if( !aCust.get() )
        {
            std::cout << "Barber Error: Customer is null ?? terminating...";
            return 1;
        }
        std::cout << "Barber is now cutting hair for customer " << *aCust << "...\n";
        ::Sleep( 600 );
        std::cout << " finished\n";
    }
}


// =================================================
//      BarberShop
// =================================================

BarberShop::BarberShop()
:m_BarberSleepEvt(NULL),
    m_Mutex(NULL),
    m_Head(0),
    m_Tail(0)
{
    m_BarberSleepEvt = ::CreateEvent( NULL, FALSE, FALSE, NULL);
    m_Mutex = ::CreateMutex( NULL, FALSE, NULL );
    std::auto_ptr aBarb( new Barber(*this) );
    m_Barber = aBarb;
    m_Barber->Start();
}


void BarberShop::GetNextCusomer( std::auto_ptr & outCust)
{
    DWORD aResult;

    do
    {
        aResult = ::WaitForSingleObject( m_Mutex, INFINITE );
        if( aResult != WAIT_OBJECT_0 )
        {
            std::cout << "BarberShop::GetNextCusomer. Error while waiting for mutex!\n";
            return;
        }
        // If the queue is empty, go to sleep. When a customer arrives, we will be woken up
        if( m_Head == m_Tail)
        {
            ::ReleaseMutex( m_Mutex );
            aResult = ::WaitForSingleObject( m_BarberSleepEvt, INFINITE );
            if( aResult != WAIT_OBJECT_0 )
            {
                std::cout << "BarberShop::GetNextCusomer. Error while waiting for event!\n";
                return;
            }
        }
        else
        {
            // There are some waiting customers. Get the one from the head
            outCust = m_WaitingCustomers[m_Head];
            incr( m_Head );
            ::ReleaseMutex( m_Mutex );
            return;
        }
    }
    while(1);
}


void BarberShop::NeedsHaircut( std::auto_ptr & inCust)
{
    DWORD aResult;
    int aNextPos;
    bool aQueueWasEmpty;

    // Get the mutex...
    aResult = ::WaitForSingleObject( m_Mutex, INFINITE );
    if( aResult != WAIT_OBJECT_0 )
    {
        std::cout << "BarberShop::GetNextCusomer. Error while waiting for mutex!\n";
        return;
    }

    // Check if the queue was empty. If the queue was empty, then we need to signal the
    // sleeping barber that there is a waiting customer
    aQueueWasEmpty = m_Tail == m_Head;
    aNextPos = m_Tail;
    incr(aNextPos );
    if( aNextPos == m_Head )
    {
        std::cout << "BarberShop::NeedsHaircut. Cant accept customer " << *inCust << " as Queue is full..\n";
        ::ReleaseMutex( m_Mutex );
        return;
    }
    // queue is not full. Add the customer to the tail
    m_WaitingCustomers[ m_Tail ] = inCust;
    m_Tail = aNextPos;
    ::ReleaseMutex( m_Mutex );
    if( aQueueWasEmpty )
    {
        ::SetEvent(m_BarberSleepEvt);
    }
    return;
}



// ====================================================
//    Application
// ====================================================
int main(int, char **)
{
    std::cout << "Hello, everyone. I am now running barber shop simulation\n";

    BarberShop aShop;
    for(int i=0; i < 1000; i++)
    {
        std::auto_ptr aCust( new Customer(i));
        std::cout << "adding customer # " << i << " to shop\n";
        aShop.NeedsHaircut( aCust );
        ::srand(time(NULL));
        int aCount = ::rand()%100 + 10;
        ::Sleep( 700 ); //aCount );
    }
    ::Sleep(10000);
}