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?