Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Shared lock
//g++ 5.4.0 #include <iostream> #include <memory> #include <mutex> #include <unordered_map> std::shared_ptr<std::mutex> GetLock(int id) { static std::unordered_map<int, std::weak_ptr<std::mutex>> map; static std::mutex map_lock; std::lock_guard<std::mutex> guard{map_lock}; auto i = map.find(id); if (i != map.end()) { std::cout << "Retrieving id = " << id << std::endl; return i->second.lock(); } else { std::cout << "Adding id = " << id << std::endl; auto lock = std::shared_ptr<std::mutex>( new std::mutex{}, [&map, &map_lock, id](std::mutex*) { std::cout << "Removing id = " << id << std::endl; std::lock_guard<std::mutex> guard{map_lock}; map.erase(id); } ); map.insert({id, lock}); return lock; } } int main() { auto lock1 = GetLock(10); auto lock2 = GetLock(10); }
run
|
edit
|
history
|
help
0
ExceptionWhat
Scope guarding
File System
Teatime Snack
scemo le
3
prototype match
merge-sort
Test 12(2021)
minmax