I have a function called "producer" that takes a class object as argument. I am trying to create thread for producer using boost::thread. However it is causing error because of the class object that I am passing as argument. I cannot figure out why is it giving error. If I remove function arguments and let it pass in as global variable, it works fine. Below is my code.
BlockingQueue.h
#ifndef BLOCKINGQUEUE_H_
#define BLOCKINGQUEUE_H_
#include <queue>
#include <iostream>
#include <boost/thread.hpp>
template<class T>
class BlockingQueue
{
private:
std::queue<T> m_queBlockingQueue;
boost::condition_variable m_cvSignal;
boost::mutex m_mtxSync;
public:
BlockingQueue();
bool isEmpty();
T& popElement();
void pushElement(T nElement);
virtual ~BlockingQueue();
};
template<class T>
BlockingQueue<T>::BlockingQueue()
{
}
template<class T>
bool BlockingQueue<T>::isEmpty()
{
bool bEmpty;
boost::mutex::scoped_lock lock(m_mtxSync);
m_cvSignal.wait(lock);
bEmpty = m_queBlockingQueue.empty();
return bEmpty;
}
template<class T>
T& BlockingQueue<T>::popElement()
{
boost::mutex::scoped_lock lock(m_mtxSync);
while (m_queBlockingQueue.empty())
{
m_cvSignal.wait(lock);
}
T& nElement = m_queBlockingQueue.front();
m_queBlockingQueue.pop();
return nElement;
}
template<class T>
void BlockingQueue<T>::pushElement(T nElement)
{
boost::mutex::scoped_lock lock(m_mtxSync);
m_queBlockingQueue.push(nElement);
m_cvSignal.notify_one();
}
template<class T>
BlockingQueue<T>::~BlockingQueue()
{
}
#endif /* BLOCKINGQUEUE_H_ */
Main.cpp
#include "BlockingQueue.h"
#include <iostream>
using namespace std;
void producer (BlockingQueue<int>& blockingQueue)
{
for (int i=0; i<100; i++)
{
cout<<"Producer about to push("<<i<<")..."<<endl;
blockingQueue.pushElement(i);
sleep(1);
}
}
void consumer (BlockingQueue<int>& blockingQueue)
{
for (int i=0; i<100; i++)
{
cout<<"Consumer received: "<<blockingQueue.popElement()<<endl;
sleep(3);
}
}
int main ()
{
BlockingQueue<int> blockingQueue;
cout<<"Program started..."<<endl;
cout.flush();
boost::thread tConsumer(consumer, blockingQueue);
boost::thread tProducer(producer, blockingQueue);
tProducer.join();
tConsumer.join();
return 0;
}
The errors that I am getting are something like:
1) no known conversion for argument 1 from ‘const BlockingQueue’ to ‘BlockingQueue&’ 2) BlockingQueue::BlockingQueue(BlockingQueue&) within this context 3) no matching function for call to ‘BlockingQueue::BlockingQueue(const BlockingQueue&)’
I have other errors like: thread.hpp:148:47: error: initializing argument 1 of ‘static boost::detail::thread_data_ptr boost::thread::make_thread_info(F) [with F = boost::_bi::bind_t&), boost::_bi::list1 > > >, boost::detail::thread_data_ptr = boost::shared_ptr]’
Is there some function like copy constructor etc in my class which is missing or what. If I use my code to pass primitive data types like int, double it works fine. It was some issue with my class "BlockingQueue".