recursive_timed_mutex.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright Oliver Kowalke 2013.
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. //
  6. // based on boost::interprocess::sync::interprocess_spinlock
  7. #ifndef BOOST_FIBERS_RECURSIVE_TIMED_MUTEX_H
  8. #define BOOST_FIBERS_RECURSIVE_TIMED_MUTEX_H
  9. #include <chrono>
  10. #include <cstddef>
  11. #include <boost/config.hpp>
  12. #include <boost/assert.hpp>
  13. #include <boost/fiber/context.hpp>
  14. #include <boost/fiber/detail/config.hpp>
  15. #include <boost/fiber/detail/convert.hpp>
  16. #include <boost/fiber/detail/spinlock.hpp>
  17. #include <boost/fiber/waker.hpp>
  18. #ifdef BOOST_HAS_ABI_HEADERS
  19. # include BOOST_ABI_PREFIX
  20. #endif
  21. #ifdef _MSC_VER
  22. # pragma warning(push)
  23. # pragma warning(disable:4251)
  24. #endif
  25. namespace boost {
  26. namespace fibers {
  27. class condition_variable;
  28. class BOOST_FIBERS_DECL recursive_timed_mutex {
  29. private:
  30. friend class condition_variable;
  31. detail::spinlock wait_queue_splk_{};
  32. wait_queue wait_queue_{};
  33. context * owner_{ nullptr };
  34. std::size_t count_{ 0 };
  35. bool try_lock_until_( std::chrono::steady_clock::time_point const& timeout_time) noexcept;
  36. public:
  37. recursive_timed_mutex() = default;
  38. ~recursive_timed_mutex() {
  39. BOOST_ASSERT( nullptr == owner_);
  40. BOOST_ASSERT( 0 == count_);
  41. BOOST_ASSERT( wait_queue_.empty() );
  42. }
  43. recursive_timed_mutex( recursive_timed_mutex const&) = delete;
  44. recursive_timed_mutex & operator=( recursive_timed_mutex const&) = delete;
  45. void lock();
  46. bool try_lock() noexcept;
  47. template< typename Clock, typename Duration >
  48. bool try_lock_until( std::chrono::time_point< Clock, Duration > const& timeout_time_) {
  49. std::chrono::steady_clock::time_point timeout_time = detail::convert( timeout_time_);
  50. return try_lock_until_( timeout_time);
  51. }
  52. template< typename Rep, typename Period >
  53. bool try_lock_for( std::chrono::duration< Rep, Period > const& timeout_duration) {
  54. return try_lock_until_( std::chrono::steady_clock::now() + timeout_duration);
  55. }
  56. void unlock();
  57. };
  58. }}
  59. #ifdef _MSC_VER
  60. # pragma warning(pop)
  61. #endif
  62. #ifdef BOOST_HAS_ABI_HEADERS
  63. # include BOOST_ABI_SUFFIX
  64. #endif
  65. #endif // BOOST_FIBERS_RECURSIVE_TIMED_MUTEX_H