我的建议是首先研究如何使用线程安全队列,然后考虑使用 boost::condition 信号来提供更多控制。
这是一个如何构建线程安全队列的示例:
#pragma once
#include <queue>
template<typename T>
class thread_safe_queue
{
queue<T> m_queue;
pthread_mutex_t m_mutex;
pthread_cond_t m_condv;
public:
thread_safe_queue() {
pthread_mutex_init(&m_mutex, NULL);
pthread_cond_init(&m_condv, NULL);
}
~thread_safe_queue() {
pthread_mutex_destroy(&m_mutex);
pthread_cond_destroy(&m_condv);
}
void push(T& item) {
pthread_mutex_lock(&m_mutex);
T itemcpy = std::move(item);
m_queue.push(std::move(itemcpy));
pthread_cond_signal(&m_condv);
pthread_mutex_unlock(&m_mutex);
}
T pop() {
pthread_mutex_lock(&m_mutex);
while (m_queue.size() == 0) {
pthread_cond_wait(&m_condv, &m_mutex);
}
T& _item = m_queue.front();
T itemcpy = std::move(_item);
m_queue.pop();
pthread_mutex_unlock(&m_mutex);
return itemcpy;
}
int size() {
pthread_mutex_lock(&m_mutex);
int size = m_queue.size();
pthread_mutex_unlock(&m_mutex);
return size;
}
};
这就是你实例化它的方式:
thread_safe_queue<myclass> myqueue;
如果您想使用事件信号,请考虑使用 boost::condition - fx。像这样:
#include <boost/thread/condition.hpp>
#include <boost/thread/mutex.hpp>
boost::mutex mtxWait;
boost::condition cndSignalQueueHasNewEntry;
bool WaitForQueueSignal(long milliseconds)
{
boost::mutex::scoped_lock mtxWaitLock(mtxWait);
boost::posix_time::time_duration wait_duration = boost::posix_time::milliseconds(milliseconds); // http://www.boost.org/doc/libs/1_34_0/doc/html/date_time/posix_time.html
boost::system_time const timeout=boost::get_system_time()+wait_duration; // http://www.justsoftwaresolutions.co.uk/threading/condition-variable-spurious-wakes.html
return cndSignalQueueHasNewEntry.timed_wait(mtxWait,timeout); // wait until signal notify_one or timeout
}
这就是你可以发出信号的方式
cndSignalQueueHasNewEntry.notify_one();
这就是你可以等待信号的方式
bool bResult = WaitForQueueSignal(10000); // timeout after 10 seconds