fork download
  1. #include <iostream>
  2. #include <mutex>
  3. #include <thread>
  4. #include <unistd.h>
  5.  
  6. using namespace std;
  7.  
  8. mutex mtx;
  9.  
  10. void function(int num) {
  11. cout << "waiting for the lock in thread " << this_thread::get_id() << endl;
  12. lock_guard<mutex> lock(mtx);
  13. sleep(2);
  14. cout << "Acquired the lock in thread " << this_thread::get_id() << endl;
  15. return;
  16. }
  17.  
  18. int main() {
  19. thread t1(function, 5);
  20. thread t2(function, 5);
  21.  
  22. t1.join();
  23. t2.join();
  24. return 0;
  25. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
waiting for the lock in thread 22994000369408
waiting for the lock in thread 22994002470656
Acquired the lock in thread 22994000369408
Acquired the lock in thread 22994002470656