問題描述
來自 boost 庫的 Circular_buffer 不是線程安全的.所以我將 boost::circular_buffer 對象包裝在一個類中,如下所示.線程之間的互斥是通過使用條件變量、互斥鎖和鎖獲取/釋放來實現(xiàn)的(我認(rèn)為).這個實現(xiàn)線程安全嗎?
Circular_buffer from boost library is not thread-safe. So I wrapped boost::circular_buffer object in a class as shown below. Mutual exclusion between the threads is achieved (I think) by using conditional variables, a mutex and a lock acquisition/release. Is this implementation thread safe?
#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;
};
Edit 這現(xiàn)在是一個模板類,它接受任何類型的對象(不僅僅是 cv::Mat
對象).
Edit This is now a template class, which accepts an object of any type (not just cv::Mat
object).
推薦答案
是.
如果您使用相同的鎖鎖定所有公共方法,它將是線程安全的.
Yes.
If you lock all the public methods with the same lock it will be threadsafe.
您可以考慮使用讀寫鎖,如果您使用它可能會有更好的性能有很多并發(fā)讀者.
You could consider using read-write locks, which may have better performance if you have a lot of concurrent readers.
如果你沒有很多讀者,它只會增加開銷,但可能值得檢查選項和測試.
If you don't have a lot of readers, it will just add overhead, but may be worth checking the option and testing.
這篇關(guān)于循環(huán)緩沖區(qū)的線程安全實現(xiàn)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!