分享

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

 禁忌石 2019-05-28

#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 

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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多