try_lock_until_pass.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is dual licensed under the MIT and the University of Illinois Open
  6. // Source Licenses. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. // Copyright (C) 2011 Vicente J. Botet Escriba
  10. //
  11. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  12. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  13. // <boost/thread/locks.hpp>
  14. // template <class Mutex> class unique_lock;
  15. // template <class Clock, class Duration>
  16. // bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_time);
  17. #include <boost/thread/lock_types.hpp>
  18. #include <boost/thread/mutex.hpp>
  19. #include <boost/detail/lightweight_test.hpp>
  20. #if defined BOOST_THREAD_USES_CHRONO
  21. bool try_lock_until_called = false;
  22. struct mutex
  23. {
  24. template <class Clock, class Duration>
  25. bool try_lock_until(const boost::chrono::time_point<Clock, Duration>& abs_time)
  26. {
  27. typedef boost::chrono::milliseconds ms;
  28. BOOST_TEST(Clock::now() - abs_time < ms(5));
  29. try_lock_until_called = !try_lock_until_called;
  30. return try_lock_until_called;
  31. }
  32. void unlock()
  33. {
  34. }
  35. };
  36. mutex m;
  37. int main()
  38. {
  39. typedef boost::chrono::steady_clock Clock;
  40. boost::unique_lock<mutex> lk(m, boost::defer_lock);
  41. BOOST_TEST(lk.try_lock_until(Clock::now()) == true);
  42. BOOST_TEST(try_lock_until_called == true);
  43. BOOST_TEST(lk.owns_lock() == true);
  44. try
  45. {
  46. lk.try_lock_until(Clock::now());
  47. BOOST_TEST(false);
  48. }
  49. catch (boost::system::system_error& e)
  50. {
  51. BOOST_TEST(e.code().value() == boost::system::errc::resource_deadlock_would_occur);
  52. }
  53. lk.unlock();
  54. BOOST_TEST(lk.try_lock_until(Clock::now()) == false);
  55. BOOST_TEST(try_lock_until_called == false);
  56. BOOST_TEST(lk.owns_lock() == false);
  57. lk.release();
  58. try
  59. {
  60. lk.try_lock_until(Clock::now());
  61. BOOST_TEST(false);
  62. }
  63. catch (boost::system::system_error& e)
  64. {
  65. BOOST_TEST(e.code().value() == boost::system::errc::operation_not_permitted);
  66. }
  67. return boost::report_errors();
  68. }
  69. #else
  70. #error "Test not applicable: BOOST_THREAD_USES_CHRONO not defined for this platform as not supported"
  71. #endif