try_lock_for_pass.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 Rep, class Period>
  16. // bool try_lock_for(const chrono::duration<Rep, Period>& rel_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_for_called = false;
  22. typedef boost::chrono::milliseconds ms;
  23. struct mutex
  24. {
  25. template <class Rep, class Period>
  26. bool try_lock_for(const boost::chrono::duration<Rep, Period>& rel_time)
  27. {
  28. BOOST_TEST(rel_time == ms(5));
  29. try_lock_for_called = !try_lock_for_called;
  30. return try_lock_for_called;
  31. }
  32. void unlock()
  33. {
  34. }
  35. };
  36. mutex m;
  37. int main()
  38. {
  39. boost::unique_lock<mutex> lk(m, boost::defer_lock);
  40. BOOST_TEST(lk.try_lock_for(ms(5)) == true);
  41. BOOST_TEST(try_lock_for_called == true);
  42. BOOST_TEST(lk.owns_lock() == true);
  43. try
  44. {
  45. lk.try_lock_for(ms(5));
  46. BOOST_TEST(false);
  47. }
  48. catch (boost::system::system_error& e)
  49. {
  50. BOOST_TEST(e.code().value() == boost::system::errc::resource_deadlock_would_occur);
  51. }
  52. lk.unlock();
  53. BOOST_TEST(lk.try_lock_for(ms(5)) == false);
  54. BOOST_TEST(try_lock_for_called == false);
  55. BOOST_TEST(lk.owns_lock() == false);
  56. lk.release();
  57. try
  58. {
  59. lk.try_lock_for(ms(5));
  60. BOOST_TEST(false);
  61. }
  62. catch (boost::system::system_error& e)
  63. {
  64. BOOST_TEST(e.code().value() == boost::system::errc::operation_not_permitted);
  65. }
  66. return boost::report_errors();
  67. }
  68. #else
  69. #error "Test not applicable: BOOST_THREAD_USES_CHRONO not defined for this platform as not supported"
  70. #endif