fork(1) download
  1. #include <iostream>
  2. #include <thread>
  3. #include <mutex>
  4. #include <atomic>
  5. #include <chrono>
  6. using namespace std;
  7.  
  8. struct info
  9. {
  10. std::mutex access;
  11. string name;
  12.  
  13. };
  14.  
  15. info userStruct; //this guy shared between two threads
  16.  
  17. void f()
  18. {
  19. while (1)
  20. {
  21. std::lock_guard<std::mutex> lock(userStruct.access);
  22. userStruct.name= "TEST";
  23. }
  24. }
  25.  
  26. void g()
  27. {
  28. while (1)
  29. {
  30. {
  31. std::unique_lock<std::mutex> lock(userStruct.access, std::try_to_lock);
  32. if(!lock.owns_lock()){
  33. std::cout << "No lock" <<std::endl;
  34. }
  35. else
  36. {
  37. std::cout << "Got access:" << userStruct.name <<std::endl;
  38. }
  39. }
  40. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  41. // std::this_thread::yield();
  42. }
  43. }
  44. int main() {
  45. thread t1(f);
  46. thread t2(g);
  47. t1.join();
  48. t2.join();
  49. return 0;
  50. }
Time limit exceeded #stdin #stdout 5s 84864KB
stdin
Standard input is empty
stdout
Got access:
Got access:TEST
No lock
No lock
No lock
No lock
Got access:TEST
No lock
No lock
Got access:TEST
Got access:TEST