posix_event.hpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. //
  2. // detail/posix_event.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2011 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 ASIO_DETAIL_POSIX_EVENT_HPP
  11. #define 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 "asio/detail/config.hpp"
  16. #if defined(BOOST_HAS_PTHREADS) && !defined(ASIO_DISABLE_THREADS)
  17. #include <boost/assert.hpp>
  18. #include <pthread.h>
  19. #include "asio/detail/noncopyable.hpp"
  20. #include "asio/detail/push_options.hpp"
  21. namespace asio {
  22. namespace detail {
  23. class posix_event
  24. : private noncopyable
  25. {
  26. public:
  27. // Constructor.
  28. ASIO_DECL posix_event();
  29. // Destructor.
  30. ~posix_event()
  31. {
  32. ::pthread_cond_destroy(&cond_);
  33. }
  34. // Signal the event.
  35. template <typename Lock>
  36. void signal(Lock& lock)
  37. {
  38. BOOST_ASSERT(lock.locked());
  39. (void)lock;
  40. signalled_ = true;
  41. ::pthread_cond_signal(&cond_); // Ignore EINVAL.
  42. }
  43. // Signal the event and unlock the mutex.
  44. template <typename Lock>
  45. void signal_and_unlock(Lock& lock)
  46. {
  47. BOOST_ASSERT(lock.locked());
  48. signalled_ = true;
  49. lock.unlock();
  50. ::pthread_cond_signal(&cond_); // Ignore EINVAL.
  51. }
  52. // Reset the event.
  53. template <typename Lock>
  54. void clear(Lock& lock)
  55. {
  56. BOOST_ASSERT(lock.locked());
  57. (void)lock;
  58. signalled_ = false;
  59. }
  60. // Wait for the event to become signalled.
  61. template <typename Lock>
  62. void wait(Lock& lock)
  63. {
  64. BOOST_ASSERT(lock.locked());
  65. while (!signalled_)
  66. ::pthread_cond_wait(&cond_, &lock.mutex().mutex_); // Ignore EINVAL.
  67. }
  68. private:
  69. ::pthread_cond_t cond_;
  70. bool signalled_;
  71. };
  72. } // namespace detail
  73. } // namespace asio
  74. #include "asio/detail/pop_options.hpp"
  75. #if defined(ASIO_HEADER_ONLY)
  76. # include "asio/detail/impl/posix_event.ipp"
  77. #endif // defined(ASIO_HEADER_ONLY)
  78. #endif // defined(BOOST_HAS_PTHREADS) && !defined(ASIO_DISABLE_THREADS)
  79. #endif // ASIO_DETAIL_POSIX_EVENT_HPP