fork download
  1. #include <mutex>
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. struct LoudMutex : std::mutex {
  6. using std::mutex::mutex;
  7. void lock() { cout << "Locking!" << endl; this->mutex::lock(); }
  8.  
  9. bool try_lock() { cout << "Trying to lock: " << endl;
  10. bool success = this->mutex::try_lock();
  11. cout << success << endl;
  12. return success; }
  13.  
  14. void unlock() { cout << "Unlocking!" << endl; this->mutex::unlock(); }
  15. };
  16.  
  17. int main() {
  18. LoudMutex m;
  19.  
  20. {
  21. cout << endl << "Case 1" << endl;
  22. std::unique_lock<LoudMutex> l(m);
  23. cout << "Hello!" << endl;
  24. }
  25.  
  26. {
  27. cout << endl << "Case 2" << endl;
  28. auto l = std::unique_lock<LoudMutex>(m);
  29. cout << "Hello!" << endl;
  30. }
  31.  
  32. {
  33. cout << endl << "Case 3" << endl;
  34. // OOPS! this declares a function `l`, but doesn't invoke any methods!
  35. auto l(std::unique_lock<LoudMutex>(m));
  36. cout << "Hello!" << endl;
  37. }
  38.  
  39. return 0;
  40. }
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
Case 1
Locking!
Hello!
Unlocking!

Case 2
Locking!
Hello!
Unlocking!

Case 3
Hello!