recursive_lw_mutex.hpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /* Copyright 2006-2013 Joaquin M Lopez Munoz.
  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. * See http://www.boost.org/libs/flyweight for library home page.
  7. */
  8. #ifndef BOOST_FLYWEIGHT_DETAIL_RECURSIVE_LW_MUTEX_HPP
  9. #define BOOST_FLYWEIGHT_DETAIL_RECURSIVE_LW_MUTEX_HPP
  10. #if defined(_MSC_VER)
  11. #pragma once
  12. #endif
  13. /* Recursive lightweight mutex. Relies entirely on
  14. * boost::detail::lightweight_mutex, except in Pthreads, where we
  15. * explicitly use the PTHREAD_MUTEX_RECURSIVE attribute
  16. * (lightweight_mutex uses the default mutex type instead).
  17. */
  18. #include <boost/config.hpp>
  19. #if !defined(BOOST_HAS_PTHREADS)
  20. #include <boost/detail/lightweight_mutex.hpp>
  21. namespace boost{
  22. namespace flyweights{
  23. namespace detail{
  24. typedef boost::detail::lightweight_mutex recursive_lightweight_mutex;
  25. } /* namespace flyweights::detail */
  26. } /* namespace flyweights */
  27. } /* namespace boost */
  28. #else
  29. /* code shamelessly ripped from <boost/detail/lwm_pthreads.hpp> */
  30. #include <boost/assert.hpp>
  31. #include <boost/noncopyable.hpp>
  32. #include <pthread.h>
  33. namespace boost{
  34. namespace flyweights{
  35. namespace detail{
  36. struct recursive_lightweight_mutex:noncopyable
  37. {
  38. recursive_lightweight_mutex()
  39. {
  40. pthread_mutexattr_t attr;
  41. BOOST_VERIFY(pthread_mutexattr_init(&attr)==0);
  42. BOOST_VERIFY(pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE)==0);
  43. BOOST_VERIFY(pthread_mutex_init(&m_,&attr)==0);
  44. BOOST_VERIFY(pthread_mutexattr_destroy(&attr)==0);
  45. }
  46. ~recursive_lightweight_mutex(){pthread_mutex_destroy(&m_);}
  47. struct scoped_lock;
  48. friend struct scoped_lock;
  49. struct scoped_lock:noncopyable
  50. {
  51. public:
  52. scoped_lock(recursive_lightweight_mutex& m):m_(m.m_)
  53. {
  54. BOOST_VERIFY(pthread_mutex_lock(&m_)==0);
  55. }
  56. ~scoped_lock(){BOOST_VERIFY(pthread_mutex_unlock(&m_)==0);}
  57. private:
  58. pthread_mutex_t& m_;
  59. };
  60. private:
  61. pthread_mutex_t m_;
  62. };
  63. } /* namespace flyweights::detail */
  64. } /* namespace flyweights */
  65. } /* namespace boost */
  66. #endif
  67. #endif