线程安全的实现循环缓冲区 [英] Thread safe implementation of circular buffer

查看:426
本文介绍了线程安全的实现循环缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Circular_buffer从boost库不是线程安全的。所以,我在一个类包装的boost :: circular_buffer对象,如下图所示。线程之间的相互排斥是通过使用条件变量,互斥和锁获取/释放完成(我认为)。这是实现线程安全的?

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;
};

修改这是现在一个模板类,它可以接受任何类型(而不仅仅是 CV ::垫)对象的对象。

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.

您可以考虑使用 读写锁 ,其中可能有,如果你更好的性能有很多并发读者。

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.

这篇关于线程安全的实现循环缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆