mardi 21 août 2018

Is there a simple solution for a ~80% write / 20% read threadsafe unordered map?

I am looking to implement a map of simple struct with 2 writers and multiple readers. To make it thread-safe, I am currently using mutex with unique locks (my code below). There will only be insert and edit operations on the structs and no erase.

However, because write operations will be much more frequent than read operations (around ~1m write operations vs 15-20,000 read operations in the same time period), I am worried that use of unique locks will affect the performance of the read operations.

I am wondering if there is a better / simpler way to implement a simple concurrent map for my problem? For example, would it be better to lock just the struct itself rather than the entire map each time a write / read operation is performed?

I have looked into Intel TBB concurrent unordered map and Pershing's Junction map but would prefer to stick with just using the STL if it is possible.

I am using C++11 so shared_lock is not available. I contemplated using boost::shared_lock for the read operations, but I understand from this post that the cost of locking a shared_mutex is higher than that of a plain one.

#include <mutex>

struct Foo
{
    double bar1 = 0;
    long bar2 = 0;
};

class FooMap
{
    std::mutex mMutex;
    std::unordered_map<long, Foo> mMap;

public:
    Foo get(long const& key) 
    {
        std::unique_lock<std::mutex> lock(mMutex);
        return mMap[key];
    }

    void set(long const& key, double a, long b) 
    {
        std::unique_lock<std::mutex> lock(mMutex);
        mMap[key].bar1 = a;
        mMap[key].bar2 = b;
    }

};

Aucun commentaire:

Enregistrer un commentaire