0

I have the following mutex manager which I aims to lock/unlock mutex given a topic name. I want to be able to lock/unlock mutexes depending on a specific tag (in this example a string). What I am doing is simply mapping a string to a mutex. Then, the outside world would invoke MutexManager::lock on tag name, then the MutexManager would lock the correct mutex.

Is this the way to do it, or should I instead be creating a map of std::unique_lock<std::mutex>

#include <iostream>
#include <unordered_map>
#include <mutex>

class MutexManager {
    public:
    std::unordered_map<std::string, std::mutex> mutexes;

    std::unique_lock<std::mutex> lock_mutex(const std::string& name) {

        try {
            std::unique_lock<std::mutex> lock(mutexes.at(name));
            return lock;
        } catch (...) {
            std::cout << "Failed to acquire lock";
        }
    }
    void unlock_mutex(std::unique_lock<std::mutex> locked_mutex) 
    {

        try {
            locked_mutex.unlock();
        } catch (...) {
            std::cout << "Failed to release lock.";
        }
    }
    
    void add_mutex(std::string topic) { 
        mutexes[topic]; // is that really the solution?
    }


};

int main()
{
    MutexManager mutexManager;
    mutexManager.add_mutex("test"); 
    
    auto& mutexx  = mutexManager.mutexes.at("test");
    
    
    return 0;
}

My concern with the above is if I got two threads where thread 1 runs lock followed by thread2 :

thread 1:

mutexManager.lock("test");

thread 2:

mutexManager.lock("test");

Will thread two be blocked untill thread 1 has released the lock ? In other words, does the locks above target the same mutex given we got the same topic?

ATK
  • 1,296
  • 10
  • 26
  • use `mutexManager.mutexes["test"]` to create an element. In general it'd be easier to use a pointer rather than storing the mutex directly – Alan Birtles Oct 01 '22 at 15:32
  • the linked thread does also seem to suggest try_emplace . I did also try that, and it did not work? – ATK Oct 01 '22 at 15:33
  • 1
    IIRC mutexes are not copyable, and this creates problems with many data structures, std::map may work better than unordered_map, but I'm not sure. The same restrictions possibly apply to unique_lock. You can workaround many problems by storing pointer to mutex instead! – Sven Nilsson Oct 01 '22 at 15:36
  • I have rephrased the question and is now not a duplicate. – ATK Oct 01 '22 at 15:42
  • using a unique_ptr of mutex instead and then emplacing it just return a null mutex? – ATK Oct 01 '22 at 15:54
  • the solution you provide with [] is not helping since it is not creating a list of mutexes rather it keeps refering back to the same one. Please read my question before voting for a duplicate!! – ATK Oct 01 '22 at 15:55
  • it'll make a new mutex if you use a different name? – Alan Birtles Oct 01 '22 at 16:10
  • `try_emplace` does work too: https://godbolt.org/z/bvMhrEG4z – Alan Birtles Oct 01 '22 at 16:13

0 Answers0