pthread_mutex_scoped_lock.hpp 1.7 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/config/abi_prefix.hpp>
  11. namespace boost
  12. {
  13. namespace pthread
  14. {
  15. class pthread_mutex_scoped_lock
  16. {
  17. pthread_mutex_t* m;
  18. bool locked;
  19. public:
  20. explicit pthread_mutex_scoped_lock(pthread_mutex_t* m_) BOOST_NOEXCEPT:
  21. m(m_),locked(true)
  22. {
  23. BOOST_VERIFY(!pthread_mutex_lock(m));
  24. }
  25. void unlock() BOOST_NOEXCEPT
  26. {
  27. BOOST_VERIFY(!pthread_mutex_unlock(m));
  28. locked=false;
  29. }
  30. void unlock_if_locked() BOOST_NOEXCEPT
  31. {
  32. if(locked)
  33. {
  34. unlock();
  35. }
  36. }
  37. ~pthread_mutex_scoped_lock() BOOST_NOEXCEPT
  38. {
  39. if(locked)
  40. {
  41. unlock();
  42. }
  43. }
  44. };
  45. class pthread_mutex_scoped_unlock
  46. {
  47. pthread_mutex_t* m;
  48. public:
  49. explicit pthread_mutex_scoped_unlock(pthread_mutex_t* m_) BOOST_NOEXCEPT:
  50. m(m_)
  51. {
  52. BOOST_VERIFY(!pthread_mutex_unlock(m));
  53. }
  54. ~pthread_mutex_scoped_unlock() BOOST_NOEXCEPT
  55. {
  56. BOOST_VERIFY(!pthread_mutex_lock(m));
  57. }
  58. };
  59. }
  60. }
  61. #include <boost/config/abi_suffix.hpp>
  62. #endif