try_lock.pass.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // UNSUPPORTED: libcpp-has-no-threads
  10. // <mutex>
  11. // class recursive_mutex;
  12. // bool try_lock();
  13. #include <mutex>
  14. #include <thread>
  15. #include <cstdlib>
  16. #include <cassert>
  17. #include "test_macros.h"
  18. std::recursive_mutex m;
  19. typedef std::chrono::system_clock Clock;
  20. typedef Clock::time_point time_point;
  21. typedef Clock::duration duration;
  22. typedef std::chrono::milliseconds ms;
  23. typedef std::chrono::nanoseconds ns;
  24. void f()
  25. {
  26. time_point t0 = Clock::now();
  27. assert(!m.try_lock());
  28. assert(!m.try_lock());
  29. assert(!m.try_lock());
  30. while(!m.try_lock())
  31. ;
  32. time_point t1 = Clock::now();
  33. assert(m.try_lock());
  34. m.unlock();
  35. m.unlock();
  36. ns d = t1 - t0 - ms(250);
  37. assert(d < ms(200)); // within 200ms
  38. }
  39. int main(int, char**)
  40. {
  41. m.lock();
  42. std::thread t(f);
  43. std::this_thread::sleep_for(ms(250));
  44. m.unlock();
  45. t.join();
  46. return 0;
  47. }