posix_event.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. //
  2. // posix_event.hpp
  3. // ~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. #ifndef BOOST_ASIO_DETAIL_POSIX_EVENT_HPP
  11. #define BOOST_ASIO_DETAIL_POSIX_EVENT_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <boost/asio/detail/push_options.hpp>
  16. #include <boost/asio/detail/push_options.hpp>
  17. #include <boost/config.hpp>
  18. #include <boost/system/system_error.hpp>
  19. #include <boost/asio/detail/pop_options.hpp>
  20. #if defined(BOOST_HAS_PTHREADS)
  21. #include <boost/asio/detail/push_options.hpp>
  22. #include <boost/assert.hpp>
  23. #include <boost/throw_exception.hpp>
  24. #include <pthread.h>
  25. #include <boost/asio/detail/pop_options.hpp>
  26. #include <boost/asio/error.hpp>
  27. #include <boost/asio/detail/noncopyable.hpp>
  28. namespace boost {
  29. namespace asio {
  30. namespace detail {
  31. class posix_event
  32. : private noncopyable
  33. {
  34. public:
  35. // Constructor.
  36. posix_event()
  37. : signalled_(false)
  38. {
  39. int error = ::pthread_cond_init(&cond_, 0);
  40. if (error != 0)
  41. {
  42. boost::system::system_error e(
  43. boost::system::error_code(error,
  44. boost::asio::error::get_system_category()),
  45. "event");
  46. boost::throw_exception(e);
  47. }
  48. }
  49. // Destructor.
  50. ~posix_event()
  51. {
  52. ::pthread_cond_destroy(&cond_);
  53. }
  54. // Signal the event.
  55. template <typename Lock>
  56. void signal(Lock& lock)
  57. {
  58. BOOST_ASSERT(lock.locked());
  59. (void)lock;
  60. signalled_ = true;
  61. ::pthread_cond_signal(&cond_); // Ignore EINVAL.
  62. }
  63. // Reset the event.
  64. template <typename Lock>
  65. void clear(Lock& lock)
  66. {
  67. BOOST_ASSERT(lock.locked());
  68. (void)lock;
  69. signalled_ = false;
  70. }
  71. // Wait for the event to become signalled.
  72. template <typename Lock>
  73. void wait(Lock& lock)
  74. {
  75. BOOST_ASSERT(lock.locked());
  76. while (!signalled_)
  77. ::pthread_cond_wait(&cond_, &lock.mutex().mutex_); // Ignore EINVAL.
  78. }
  79. private:
  80. ::pthread_cond_t cond_;
  81. bool signalled_;
  82. };
  83. } // namespace detail
  84. } // namespace asio
  85. } // namespace boost
  86. #endif // defined(BOOST_HAS_PTHREADS)
  87. #include <boost/asio/detail/pop_options.hpp>
  88. #endif // BOOST_ASIO_DETAIL_POSIX_EVENT_HPP