gloox  1.0.1
atomicrefcount.cpp
1 /*
2  Copyright (c) 2007-2012 by Jakob Schroeter <js@camaya.net>
3  This file is part of the gloox library. http://camaya.net/gloox
4 
5  This software is distributed under a license. The full license
6  agreement can be found in the file LICENSE in this distribution.
7  This software may not be copied, modified, sold or distributed
8  other than expressed in the named license agreement.
9 
10  This software is distributed without any warranty.
11 */
12 
13 
14 #include "atomicrefcount.h"
15 
16 #include "config.h"
17 
18 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
19 # include <windows.h>
20 #elif defined( __APPLE__ )
21 # include <libkern/OSAtomic.h>
22 #elif defined( HAVE_GCC_ATOMIC_BUILTINS )
23  // Use intrinsic functions - no #include required.
24 #else
25 # include "mutexguard.h"
26 #endif
27 
28 #ifdef _WIN32_WCE
29 # include <winbase.h>
30 #endif
31 
32 namespace gloox
33 {
34 
35  namespace util
36  {
38  : m_count( 0 )
39  {
40  }
41 
43  {
44 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
45  return (int) ::InterlockedIncrement( (volatile LONG*)&m_count );
46 #elif defined( __APPLE__ )
47  return (int) OSAtomicIncrement32Barrier( (volatile int32_t*)&m_count );
48 #elif defined( HAVE_GCC_ATOMIC_BUILTINS )
49  // Use the gcc intrinsic for atomic increment if supported.
50  return (int) __sync_add_and_fetch( &m_count, 1 );
51 #else
52  // Fallback to using a lock
53  MutexGuard m( m_lock );
54  return ++m_count;
55 #endif
56  }
57 
59  {
60 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
61  return (int) ::InterlockedDecrement( (volatile LONG*)&m_count );
62 #elif defined( __APPLE__ )
63  return (int) OSAtomicDecrement32Barrier( (volatile int32_t*)&m_count );
64 #elif defined( HAVE_GCC_ATOMIC_BUILTINS )
65  // Use the gcc intrinsic for atomic decrement if supported.
66  return (int) __sync_sub_and_fetch( &m_count, 1 );
67 #else
68  // Fallback to using a lock
69  MutexGuard m( m_lock );
70  return --m_count;
71 #endif
72  }
73 
74  }
75 
76 }
77