ScopedLock 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /* -*-c++-*- OpenThreads library, Copyright (C) 2002 - 2007 The Open Thread Group
  2. *
  3. * This library is open source and may be redistributed and/or modified under
  4. * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
  5. * (at your option) any later version. The full license is in LICENSE file
  6. * included with this distribution, and on the openscenegraph.org website.
  7. *
  8. * This library is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * OpenSceneGraph Public License for more details.
  12. */
  13. //
  14. // ScopedLock and ReverseScopedLock templates
  15. // ~~~~~~~
  16. //
  17. #ifndef _ScopedLock_
  18. #define _ScopedLock_
  19. namespace OpenThreads{
  20. template <class M> class ScopedLock
  21. {
  22. private:
  23. M& m_lock;
  24. ScopedLock(const ScopedLock&); // prevent copy
  25. ScopedLock& operator=(const ScopedLock&); // prevent assign
  26. public:
  27. explicit ScopedLock(M& m):m_lock(m) {m_lock.lock();}
  28. ~ScopedLock(){m_lock.unlock();}
  29. };
  30. template <class M> class ReverseScopedLock
  31. {
  32. private:
  33. M& m_lock;
  34. ReverseScopedLock(const ReverseScopedLock&); // prevent copy
  35. ReverseScopedLock& operator=(const ReverseScopedLock&); // prevent assign
  36. public:
  37. explicit ReverseScopedLock(M& m):m_lock(m) {m_lock.unlock();}
  38. ~ReverseScopedLock(){m_lock.lock();}
  39. };
  40. template <class M> class ScopedPointerLock
  41. {
  42. private:
  43. M* m_lock;
  44. ScopedPointerLock(const ScopedPointerLock&); // prevent copy
  45. ScopedPointerLock& operator=(const ScopedPointerLock&); // prevent assign
  46. public:
  47. explicit ScopedPointerLock(M* m):m_lock(m) { if (m_lock) m_lock->lock();}
  48. ~ScopedPointerLock(){ if (m_lock) m_lock->unlock();}
  49. };
  50. template <class M> class ReverseScopedPointerLock
  51. {
  52. private:
  53. M* m_lock;
  54. ReverseScopedPointerLock(const ReverseScopedPointerLock&); // prevent copy
  55. ReverseScopedPointerLock& operator=(const ReverseScopedPointerLock&); // prevent assign
  56. public:
  57. explicit ReverseScopedPointerLock(M* m):m_lock(m) { if (m_lock) m_lock->unlock();}
  58. ~ReverseScopedPointerLock(){ if (m_lock) m_lock->lock();}
  59. };
  60. }
  61. #endif