try_lock_pass.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. bool try_lock_called = false;
  21. struct mutex
  22. {
  23. bool try_lock()
  24. {
  25. try_lock_called = !try_lock_called;
  26. return try_lock_called;
  27. }
  28. void unlock()
  29. {
  30. }
  31. };
  32. mutex m;
  33. int main()
  34. {
  35. boost::unique_lock<mutex> lk(m, boost::defer_lock);
  36. BOOST_TEST(lk.try_lock() == true);
  37. BOOST_TEST(try_lock_called == true);
  38. BOOST_TEST(lk.owns_lock() == true);
  39. try
  40. {
  41. lk.try_lock();
  42. BOOST_TEST(false);
  43. }
  44. catch (boost::system::system_error& e)
  45. {
  46. BOOST_TEST(e.code().value() == boost::system::errc::resource_deadlock_would_occur);
  47. }
  48. lk.unlock();
  49. BOOST_TEST(lk.try_lock() == false);
  50. BOOST_TEST(try_lock_called == false);
  51. BOOST_TEST(lk.owns_lock() == false);
  52. lk.release();
  53. try
  54. {
  55. lk.try_lock();
  56. BOOST_TEST(false);
  57. }
  58. catch (boost::system::system_error& e)
  59. {
  60. BOOST_TEST(e.code().value() == boost::system::errc::operation_not_permitted);
  61. }
  62. return boost::report_errors();
  63. }