我的建议是先看看如何使用线程安全队列,然后考虑使用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
C++ 11与否?如果没有,哪个操作系统? –
它被称为信号量... –
执行此操作的典型方法是使用['condition_variable'](http://en.cppreference.com/w/cpp/thread/condition_variable)。安东尼威廉姆斯回顾了这种实现的一些细节[这里](http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html)。 –