我有一個叫做「producer」的函數,它將一個類對象作爲參數。我正在嘗試使用boost :: thread爲生產者創建線程。但是由於我作爲參數傳遞的類對象導致錯誤。我無法弄清楚它爲什麼會給出錯誤。如果我刪除函數參數並讓它作爲全局變量傳遞,它可以正常工作。以下是我的代碼。將類對象作爲參數傳遞給boost :: thread
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;
}
,我得到的錯誤是這樣的:
1)從「常量的BlockingQueue的參數1沒有已知的轉換'to'BlockingQueue &' 2)BlockingQueue :: BlockingQueue(BlockingQueue &)within this c ontext 3)調用 '的BlockingQueue BlockingQueue的::(常量的BlockingQueue &)' 不匹配函數
我有其他錯誤,如: thread.hpp:148:47:錯誤:初始化「靜態加速的說法1: :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]'
是否有一些函數像我的類中複製構造函數等丟失或什麼。如果我使用我的代碼來傳遞像int這樣的基本數據類型,那麼double就可以正常工作。這是我的班級「BlockingQueue」的一些問題。
複製構造函數是隱式生成的,如果你不阻止它 –