AtomicCount.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. /* -*- C++ -*- */
  2. /****************************************************************************
  3. ** Copyright (c) 2001-2014
  4. **
  5. ** This file is part of the QuickFIX FIX Engine
  6. **
  7. ** This file may be distributed under the terms of the quickfixengine.org
  8. ** license as defined by quickfixengine.org and appearing in the file
  9. ** LICENSE included in the packaging of this file.
  10. **
  11. ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
  12. ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  13. **
  14. ** See http://www.quickfixengine.org/LICENSE for licensing information.
  15. **
  16. ** Contact ask@quickfixengine.org if any conditions of this licensing are
  17. ** not clear to you.
  18. **
  19. ****************************************************************************/
  20. #ifndef ATOMIC_COUNT
  21. #define ATOMIC_COUNT
  22. #include "Mutex.h"
  23. namespace FIX
  24. {
  25. /// Atomic count class - consider using interlocked functions
  26. #ifdef ENABLE_BOOST_ATOMIC_COUNT
  27. #include <boost/smart_ptr/detail/atomic_count.hpp>
  28. typedef boost::detail::atomic_count atomic_count;
  29. #elif _MSC_VER
  30. //atomic counter based on interlocked functions for Win32
  31. class atomic_count
  32. {
  33. public:
  34. explicit atomic_count( long v ): m_counter( v )
  35. {
  36. }
  37. long operator++()
  38. {
  39. return ::InterlockedIncrement( &m_counter );
  40. }
  41. long operator--()
  42. {
  43. return ::InterlockedDecrement( &m_counter );
  44. }
  45. operator long() const
  46. {
  47. return static_cast<long const volatile &>( m_counter );
  48. }
  49. private:
  50. atomic_count( atomic_count const & );
  51. atomic_count & operator=( atomic_count const & );
  52. long volatile m_counter;
  53. };
  54. #else
  55. // general purpose atomic counter using mutexes
  56. class atomic_count
  57. {
  58. public:
  59. explicit atomic_count( long v ): m_counter( v )
  60. {
  61. }
  62. long operator++()
  63. {
  64. Locker _lock(m_mutex);
  65. return ++m_counter;
  66. }
  67. long operator--()
  68. {
  69. Locker _lock(m_mutex);
  70. return --m_counter;
  71. }
  72. operator long() const
  73. {
  74. return static_cast<long const volatile &>( m_counter );
  75. }
  76. private:
  77. atomic_count( atomic_count const & );
  78. atomic_count & operator=( atomic_count const & );
  79. Mutex m_mutex;
  80. long m_counter;
  81. };
  82. #endif
  83. }
  84. #endif