打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
一个线程安全的std::map封装

#pragma once

#include <map>

#include <stdint.h>

#include <opencv2/opencv.hpp>

#include <boost/thread/mutex.hpp>

#include <boost/thread/condition_variable.hpp>

template<class Key, class T>

class concurrent_map

{

private:

    std::map<Key, T> the_map;

    mutable boost::mutex the_mutex;

    boost::condition_variable the_condition_variable;

public:

    void insert(const Key &inputKey, const T &inputValue) {

        boost::mutex::scoped_lock lock(the_mutex);

        the_map.insert(std::pair<Key, T>(inputKey, inputValue));

        lock.unlock();

        the_condition_variable.notify_all();

    }

    bool empty() const {

        boost::mutex::scoped_lock lock(the_mutex);

        return the_map.empty();

    }

    bool try_get(const Key &inputKey, T &outputValue) {

        boost::mutex::scoped_lock lock(the_mutex);

        typename std::map<Key, T>::iterator it;

        it = the_map.find(inputKey);

        if(the_map.end() == it) {

            return false;

        }

        outputValue = it->second;

        return true;

    }

    void wait_and_get(const Key &inputKey, T &outputValue) {

        boost::mutex::scoped_lock lock(the_mutex);

        typename std::map<Key, T>::iterator it;

        while(the_map.end() == (it = the_map.find(inputKey))) {

            the_condition_variable.wait(lock);

        }

        outputValue = it->second;

    }

    void wait_next_insert() {

        boost::mutex::scoped_lock lock(the_mutex);

        the_condition_variable.wait(lock);

    }

    void erase(const Key &inputKey) {

        boost::mutex::scoped_lock lock(the_mutex);

        the_map.erase(inputKey);

    }

    size_t size() const {

        boost::mutex::scoped_lock lock(the_mutex);

        return the_map.size();

    }

};

--------------------- 

作者:u010584319 

来源:CSDN 

原文:https://blog.csdn.net/u010584319/article/details/77895570 

版权声明:本文为博主原创文章,转载请附上博文链接!

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
boost互斥
BOOST 线程库
boost多线程编程
C++ Boost Thread 编程指南
c++11 中函数声明 新关键字 delete的妙用之一: 搭配宏NonCopyable(ClassName) 使用
可以继承的C++ Singleton基类 · GoCalf Blog
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服