spinlock_pt.hpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #ifndef BOOST_SMART_PTR_DETAIL_SPINLOCK_PT_HPP_INCLUDED
  2. #define BOOST_SMART_PTR_DETAIL_SPINLOCK_PT_HPP_INCLUDED
  3. // MS compatible compilers support #pragma once
  4. #if defined(_MSC_VER) && (_MSC_VER >= 1020)
  5. # pragma once
  6. #endif
  7. //
  8. // Copyright (c) 2008 Peter Dimov
  9. //
  10. // Distributed under the Boost Software License, Version 1.0.
  11. // See accompanying file LICENSE_1_0.txt or copy at
  12. // http://www.boost.org/LICENSE_1_0.txt)
  13. //
  14. #include <pthread.h>
  15. namespace boost
  16. {
  17. namespace detail
  18. {
  19. class spinlock
  20. {
  21. public:
  22. pthread_mutex_t v_;
  23. public:
  24. bool try_lock()
  25. {
  26. return pthread_mutex_trylock( &v_ ) == 0;
  27. }
  28. void lock()
  29. {
  30. pthread_mutex_lock( &v_ );
  31. }
  32. void unlock()
  33. {
  34. pthread_mutex_unlock( &v_ );
  35. }
  36. public:
  37. class scoped_lock
  38. {
  39. private:
  40. spinlock & sp_;
  41. scoped_lock( scoped_lock const & );
  42. scoped_lock & operator=( scoped_lock const & );
  43. public:
  44. explicit scoped_lock( spinlock & sp ): sp_( sp )
  45. {
  46. sp.lock();
  47. }
  48. ~scoped_lock()
  49. {
  50. sp_.unlock();
  51. }
  52. };
  53. };
  54. } // namespace detail
  55. } // namespace boost
  56. #define BOOST_DETAIL_SPINLOCK_INIT { PTHREAD_MUTEX_INITIALIZER }
  57. #endif // #ifndef BOOST_SMART_PTR_DETAIL_SPINLOCK_PT_HPP_INCLUDED