pthread_mutex_scoped_lock.hpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #ifndef BOOST_PTHREAD_MUTEX_SCOPED_LOCK_HPP
  2. #define BOOST_PTHREAD_MUTEX_SCOPED_LOCK_HPP
  3. // (C) Copyright 2007-8 Anthony Williams
  4. //
  5. // Distributed under the Boost Software License, Version 1.0. (See
  6. // accompanying file LICENSE_1_0.txt or copy at
  7. // http://www.boost.org/LICENSE_1_0.txt)
  8. #include <pthread.h>
  9. #include <boost/assert.hpp>
  10. #include <boost/thread/pthread/pthread_helpers.hpp>
  11. #include <boost/config/abi_prefix.hpp>
  12. namespace boost
  13. {
  14. namespace pthread
  15. {
  16. class pthread_mutex_scoped_lock
  17. {
  18. pthread_mutex_t* m;
  19. bool locked;
  20. public:
  21. explicit pthread_mutex_scoped_lock(pthread_mutex_t* m_) BOOST_NOEXCEPT:
  22. m(m_),locked(true)
  23. {
  24. BOOST_VERIFY(!posix::pthread_mutex_lock(m));
  25. }
  26. void unlock() BOOST_NOEXCEPT
  27. {
  28. BOOST_VERIFY(!posix::pthread_mutex_unlock(m));
  29. locked=false;
  30. }
  31. void unlock_if_locked() BOOST_NOEXCEPT
  32. {
  33. if(locked)
  34. {
  35. unlock();
  36. }
  37. }
  38. ~pthread_mutex_scoped_lock() BOOST_NOEXCEPT
  39. {
  40. if(locked)
  41. {
  42. unlock();
  43. }
  44. }
  45. };
  46. class pthread_mutex_scoped_unlock
  47. {
  48. pthread_mutex_t* m;
  49. public:
  50. explicit pthread_mutex_scoped_unlock(pthread_mutex_t* m_) BOOST_NOEXCEPT:
  51. m(m_)
  52. {
  53. BOOST_VERIFY(!posix::pthread_mutex_unlock(m));
  54. }
  55. ~pthread_mutex_scoped_unlock() BOOST_NOEXCEPT
  56. {
  57. BOOST_VERIFY(!posix::pthread_mutex_lock(m));
  58. }
  59. };
  60. }
  61. }
  62. #include <boost/config/abi_suffix.hpp>
  63. #endif