我的建議是先看看如何使用線程安全隊列,然後考慮使用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)。 –