Skip to content

Instantly share code, notes, and snippets.

@mamigot
Last active April 7, 2016 16:31
Show Gist options
  • Save mamigot/31a0372149a5e9922223af02fd27e157 to your computer and use it in GitHub Desktop.
Save mamigot/31a0372149a5e9922223af02fd27e157 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <mutex>
#include <map>
using namespace std;
// Map file paths to their respective files' mutexes
map<string, shared_ptr<mutex>> fileMutexes = {};
mutex fileMutexesAccess;
shared_ptr<mutex> getFileMutex(const string& filePath){
unique_lock<mutex> lock(fileMutexesAccess);
if(fileMutexes.count(filePath)){
cout << "existed already for: " << filePath << endl;
return fileMutexes[filePath];
}else{
shared_ptr<mutex> mut(new mutex());
fileMutexes.insert(std::make_pair(filePath, mut));
return fileMutexes[filePath];
}
}
void testFileLocks(){
string samplePathA = "some/path/";
string samplePathB = "some/path/";
string samplePathC = "diff/erent/";
// A and B are the same (have similar addresses), but C is not
auto mutexA = getFileMutex(samplePathA);
auto mutexB = getFileMutex(samplePathB);
auto mutexC = getFileMutex(samplePathC);
// Shows how to use the mutex with unique_lock
unique_lock<mutex> lck(*mutexA);
// Print the addresses of the mutex pointers
cout << mutexA << endl;
cout << mutexB << endl;
cout << mutexC << endl;
}
int main(){
testFileLocks();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment