Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Shared lock
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
//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); }
g++
Show compiler warnings
[
+
] Compiler args
[
+
]
Show input
Compilation time: 1.1 sec, absolute running time: 0.3 sec, cpu time: 0.23 sec, memory peak: 3 Mb, absolute service time: 1,41 sec
edit mode
|
history
|
discussion
Adding id = 10 Retrieving id = 10 Removing id = 10