posix_mutex.hpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //
  2. // posix_mutex.hpp
  3. // ~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2010 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_MUTEX_HPP
  11. #define ASIO_DETAIL_POSIX_MUTEX_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include "asio/detail/push_options.hpp"
  16. #include "asio/detail/push_options.hpp"
  17. #include <boost/config.hpp>
  18. #include "asio/detail/pop_options.hpp"
  19. #if defined(BOOST_HAS_PTHREADS)
  20. #include "asio/detail/push_options.hpp"
  21. #include <boost/throw_exception.hpp>
  22. #include <pthread.h>
  23. #include "asio/detail/pop_options.hpp"
  24. #include "asio/error.hpp"
  25. #include "asio/system_error.hpp"
  26. #include "asio/detail/noncopyable.hpp"
  27. #include "asio/detail/scoped_lock.hpp"
  28. namespace asio {
  29. namespace detail {
  30. class posix_event;
  31. class posix_mutex
  32. : private noncopyable
  33. {
  34. public:
  35. typedef asio::detail::scoped_lock<posix_mutex> scoped_lock;
  36. // Constructor.
  37. posix_mutex()
  38. {
  39. int error = ::pthread_mutex_init(&mutex_, 0);
  40. if (error != 0)
  41. {
  42. asio::system_error e(
  43. asio::error_code(error,
  44. asio::error::get_system_category()),
  45. "mutex");
  46. boost::throw_exception(e);
  47. }
  48. }
  49. // Destructor.
  50. ~posix_mutex()
  51. {
  52. ::pthread_mutex_destroy(&mutex_); // Ignore EBUSY.
  53. }
  54. // Lock the mutex.
  55. void lock()
  56. {
  57. (void)::pthread_mutex_lock(&mutex_); // Ignore EINVAL.
  58. }
  59. // Unlock the mutex.
  60. void unlock()
  61. {
  62. (void)::pthread_mutex_unlock(&mutex_); // Ignore EINVAL.
  63. }
  64. private:
  65. friend class posix_event;
  66. ::pthread_mutex_t mutex_;
  67. };
  68. } // namespace detail
  69. } // namespace asio
  70. #endif // defined(BOOST_HAS_PTHREADS)
  71. #include "asio/detail/pop_options.hpp"
  72. #endif // ASIO_DETAIL_POSIX_MUTEX_HPP