GCS  0.2.3
gu_atomic.hpp
1 //
2 // Copyright (C) 2010 Codership Oy <info@codership.com>
3 //
4 
5 //
6 // @todo Check that the at least the following gcc versions are supported
7 // gcc version 4.1.2 20080704 (Red Hat 4.1.2-48)
8 //
9 
10 #ifndef GU_ATOMIC_HPP
11 #define GU_ATOMIC_HPP
12 
13 #include <memory>
14 
15 namespace gu
16 {
17  template <typename I>
18  class Atomic
19  {
20  public:
21  Atomic<I>(const I i = 0) : i_(i) { }
22 
23  I operator()() const
24  {
25  __sync_synchronize();
26  return i_;
27  }
28 
29  Atomic<I>& operator=(const I i)
30  {
31  i_ = i;
32  __sync_synchronize();
33  return *this;
34  }
35 
36  I fetch_and_zero()
37  {
38  return __sync_fetch_and_and(&i_, 0);
39  }
40 
41  I fetch_and_add(const I i)
42  {
43  return __sync_fetch_and_add(&i_, i);
44  }
45 
46  I add_and_fetch(const I i)
47  {
48  return __sync_add_and_fetch(&i_, i);
49  }
50 
51  I sub_and_fetch(const I i)
52  {
53  return __sync_sub_and_fetch(&i_, i);
54  }
55 
56  Atomic<I>& operator++()
57  {
58  __sync_fetch_and_add(&i_, 1);
59  return *this;
60  }
61  Atomic<I>& operator--()
62  {
63  __sync_fetch_and_sub(&i_, 1);
64  return *this;
65  }
66 
67  Atomic<I>& operator+=(const I i)
68  {
69  __sync_fetch_and_add(&i_, i);
70  return *this;
71  }
72  private:
73  I i_;
74  };
75 }
76 
77 #endif // GU_ATOMIC_HPP
Definition: gu_atomic.hpp:18