[英]Thread safe implementation of circular buffer
boost 庫中的 Circular_buffer 不是線程安全的。 所以我將 boost::circular_buffer 對象包裝在一個類中,如下所示。 線程之間的互斥是通過使用條件變量、互斥鎖和鎖獲取/釋放來實現的(我認為)。 這個實現線程安全嗎?
#include <boost/thread/condition.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
#include <boost/circular_buffer.hpp>
// Thread safe circular buffer
template <typename T>
class circ_buffer : private boost::noncopyable
{
public:
typedef boost::mutex::scoped_lock lock;
circ_buffer() {}
circ_buffer(int n) {cb.set_capacity(n);}
void send (T imdata) {
lock lk(monitor);
cb.push_back(imdata);
buffer_not_empty.notify_one();
}
T receive() {
lock lk(monitor);
while (cb.empty())
buffer_not_empty.wait(lk);
T imdata = cb.front();
cb.pop_front();
return imdata;
}
void clear() {
lock lk(monitor);
cb.clear();
}
int size() {
lock lk(monitor);
return cb.size();
}
void set_capacity(int capacity) {
lock lk(monitor);
cb.set_capacity(capacity);
}
private:
boost::condition buffer_not_empty;
boost::mutex monitor;
boost::circular_buffer<T> cb;
};
編輯這現在是一個模板類,它接受任何類型的對象(不僅僅是cv::Mat
對象)。
我認為它看起來不錯,除了在send
制作了一些毫無意義的 Mat 副本。 你不需要新的,你可以直接將send
的參數推送到你的cb。
//This implementation above is broken. You also need condition variable
//boost::condition buffer_not_full; and wait in send on available space in the circular buffer.
enter code here
void send (T imdata) {
lock lk(monitor);
while (cb.full())
buffer_not_full.wait(lk);
cb.push_back(imdata);
buffer_not_empty.notify_one();
}
T receive() {
lock lk(monitor);
while (cb.empty())
buffer_not_empty.wait(lk);
T imdata = cb.front();
cb.pop_front();
buffer_not_full.notify_one();
return imdata;
}
乍一看看起來不錯,只是您根本沒有使用buffer_not_full
條件。 您可能想要添加類似於buffer_not_empty
代碼的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.