互斥体C ++ 11的地图 [英] Map of mutex c++11

查看:49
本文介绍了互斥体C ++ 11的地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要制作一个线程安全的映射,这意味着每个值必须独立地互斥.例如,我需要能够同时从2个不同的线程中获取map["abc"]map["vf"].

I need to make a thread-safe map, where I mean that each value must be independently mutexed. For example, I need to be able to get map["abc"] and map["vf"] at the same time from 2 different threads.

我的想法是制作两个映射:一个用于数据,每个密钥用于互斥锁:

My idea is to make two maps: one for data and one for mutex for every key:

class cache
{
private:
....

    std::map<std::string, std::string> mainCache;
    std::map<std::string, std::unique_ptr<std::mutex> > mutexCache;
    std::mutex gMutex;
.....
public:
    std::string get(std::string key);

};
std::string cache::get(std::string key){
    std::mutex *m;
    gMutex.lock();
    if (mutexCache.count(key) == 0){
        mutexCache.insert(new std::unique_ptr<std::mutex>);
    }
    m = mutexCache[key];
    gMutex.unlock();
}

我发现我无法创建从字符串到互斥的映射,因为std::mutex中没有复制构造函数,因此我必须使用std::unique_ptr.但是当我编译它时,我得到了:

I find that I can't create map from string to mutex, because there is no copy constructor in std::mutex and I must use std::unique_ptr; but when I compile this I get:

/home/user/test/cache.cpp:7: error: no matching function for call to 'std::map<std::basic_string<char>, std::unique_ptr<std::mutex> >::insert(std::unique_ptr<std::mutex>*)'
         mutexCache.insert(new std::unique_ptr<std::mutex>);
                                                          ^

我该如何解决这个问题?

How do I solve this problem?

推荐答案

mutexCache.insert(new std::unique_ptr<std::mutex>)替换为:

mutexCache.emplace(key, new std::mutex);

在C ++ 14中,您应该说:

In C++14, you should say:

mutexCache.emplace(key, std::make_unique<std::mutex>());

尽管如此,整个代码非常嘈杂且笨拙.它可能看起来应该像这样:

The overall code is very noisy and inelegant, though. It should probably look like this:

std::string cache::get(std::string key)
{
    std::mutex * inner_mutex;

    {
        std::lock_guard<std::mutex> g_lk(gMutex);

        auto it = mutexCache.find(key);
        if (it == mutexCache.end())
        {
            it = mutexCache.emplace(key, std::make_unique<std::mutex>()).first;
        }
        inner_mutex = it->second.get();
    }

    {
        std::lock_guard<std::mutex> c_lk(*inner_mutex);
        return mainCache[key];
    }
}

这篇关于互斥体C ++ 11的地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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