vendredi 25 août 2023

Does anyone know a good design to manage a group of multi-read single-write resources in C++

Problem: As the title, say, I have a group of resources I need to manage in a multi-threaded C++ program. Each resource should allow multi-read single-write access. Does anyone know a good design to solve this problem?

Attempted solution: The following outlines what I'm thinking about:

Given a resource as:

struct Resource {
    //...
};

I have a global Token Manager used to manage read/write tokens:

class TokenManager {
    private:
    std::mutex m_mutex;
    std::unordered_map<int, std::shared_mutex> m_tokens;

    auto &fetch(const int key) {
        std::lock_guard g(m_mutex);
        return m_tokens[key];
    }

    public:
    auto CreateWriteToken(const int key) {
        return WriteToken{key, fetch(key)};
    }

    auto CreateReadToken(const int key) {
        return ReadToken{key, fetch(key)};
    }
};

The WriteToken represent write access to the resource, and it is derived from the Token base class:

class Token {
    Resource m_resource;
    
    protected:
    Token(const int key) {
        //open resource based on key
    };

    public:
    void Visit(const Visitor v) {
        v(m_resouce);
    }
};

class WriteToken : public Token {
    std::unique_lock m_lock;

    public:
    WriteToken(const int key, std::shared_mutex &m) : Token(key), m_lock(m) {}
};

The ReadToken represent read access to the resource:

class ReadToken : public Token {
    std::shared_lock m_lock;

    public:
    ReadToken(const int key, std::shared_mutex &m) : Token(key), m_lock(m) {}
};

Can you see any obvious flaw in this design? Do you know a better design?

Aucun commentaire:

Enregistrer un commentaire