This problem originates from a job interview which could be solved in C++ or C#. As far as I can remember it was to implement a queue that can be added to by multiple threads and accessed by multiple threads. I haven't tried it in C# yet although I think it may be easier as there is a sychronized queue already implemented?
Anyway the code is lengthy but I would appreciate comments from those more experienced in Multi-Threaded programming.
#include <iostream>
#include <boost/thread.hpp>
#include <deque>
#include <boost/thread/condition.hpp>
#include <boost/thread/mutex.hpp>
using namespace std;
//Multi-threaded queue
class multiQ
{
boost::mutex m_mutex;
deque<int> m_queue;
boost::condition_variable m_cond;
public:
void add(int i)
{
boost::lock_guard<boost::mutex> lock(m_mutex);
m_queue.push_back(i);
m_cond.notify_one();
}
int readRemove()
{
boost::unique_lock<boost::mutex> lock(m_mutex);
if (!m_queue.size())
{
m_cond.wait(lock);
}
int returnVal = m_queue.front();
m_queue.pop_front();
return returnVal;
}
};
class Qwriter
{
multiQ* mq;
void write( int ni){mq->add(ni);};
public:
Qwriter(multiQ* nq):mq(nq){};
void do_write()
{
boost::posix_time::milliseconds tTime(300);
for (int i = 0; i < 100; i++)
{
boost::this_thread::sleep(tTime);
write(i);
}
}
};
class Qreader
{
multiQ* mq;
void readRem()
{
int i = 0;
i = mq->readRemove();
cout << i << " " ;
};
public:
Qreader(multiQ* nq):mq(nq){};
void do_read()
{
for(int i=0 ; i < 100; i++)
readRem();
}
};
int main()
{
multiQ mq1;
Qreader* qRead1 = new Qreader(&mq1);
Qwriter* qWrite1 = new Qwriter(&mq1);
Qwriter* qWrite2 = new Qwriter(&mq1);
boost::thread thread1(&Qwriter::do_write, qWrite1);
boost::thread thread3(&Qwriter::do_write, qWrite2);
boost::thread thread2(&Qreader::do_read, qRead1);
thread1.join();
thread2.join();
system("PAUSE");
return 0;
}