blob: 0e07d2d94f79e866dfb670ce8c67545363434f0a [file] [log] [blame]
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ART_SRC_ATOMIC_INTEGER_H_
18#define ART_SRC_ATOMIC_INTEGER_H_
19
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070020#include "cutils/atomic.h"
21#include "cutils/atomic-inline.h"
Mathieu Chartier2fde5332012-09-14 14:51:54 -070022
23namespace art {
24
25class AtomicInteger {
26 public:
Mathieu Chartier2b82db42012-11-14 17:29:05 -080027 // Default to uninitialized
28 AtomicInteger() { }
29
Mathieu Chartier2fde5332012-09-14 14:51:54 -070030 AtomicInteger(int32_t value) : value_(value) { }
31
Mathieu Chartierd8195f12012-10-05 12:21:28 -070032 // Unsafe = operator for non atomic operations on the integer.
33 AtomicInteger& operator = (int32_t new_value) {
34 value_ = new_value;
35 return *this;
36 }
37
Mathieu Chartier2fde5332012-09-14 14:51:54 -070038 operator int32_t () const {
Mathieu Chartierd8195f12012-10-05 12:21:28 -070039 return value_;
Mathieu Chartier2fde5332012-09-14 14:51:54 -070040 }
41
42 int32_t get() const {
43 return value_;
44 }
45
46 int32_t operator += (const int32_t value) {
47 return android_atomic_add(value, &value_);
48 }
49
50 int32_t operator -= (const int32_t value) {
51 return android_atomic_add(-value, &value_);
52 }
53
54 int32_t operator |= (const int32_t value) {
55 return android_atomic_or(value, &value_);
56 }
57
58 int32_t operator &= (const int32_t value) {
59 return android_atomic_and(-value, &value_);
60 }
61
Mathieu Chartierd8195f12012-10-05 12:21:28 -070062 int32_t operator ++ (int32_t) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -070063 return android_atomic_inc(&value_);
64 }
65
Mathieu Chartierd8195f12012-10-05 12:21:28 -070066 int32_t operator -- (int32_t) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -070067 return android_atomic_dec(&value_);
68 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070069
70 int32_t operator ++ () {
71 return android_atomic_inc(&value_) + 1;
72 }
73
74 int32_t operator -- () {
75 return android_atomic_dec(&value_) - 1;
76 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -070077
78 int CompareAndSwap(int expected_value, int new_value) {
79 return android_atomic_cas(expected_value, new_value, &value_);
80 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -070081 private:
82 int32_t value_;
83};
84
85}
86
87#endif // ART_SRC_ATOMIC_INTEGER_H_