blob: 22cc7b41ed755055099267037c27ccac1dd2dddb [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:
27 AtomicInteger(int32_t value) : value_(value) { }
28
Mathieu Chartierd8195f12012-10-05 12:21:28 -070029 // Unsafe = operator for non atomic operations on the integer.
30 AtomicInteger& operator = (int32_t new_value) {
31 value_ = new_value;
32 return *this;
33 }
34
Mathieu Chartier2fde5332012-09-14 14:51:54 -070035 operator int32_t () const {
Mathieu Chartierd8195f12012-10-05 12:21:28 -070036 return value_;
Mathieu Chartier2fde5332012-09-14 14:51:54 -070037 }
38
39 int32_t get() const {
40 return value_;
41 }
42
43 int32_t operator += (const int32_t value) {
44 return android_atomic_add(value, &value_);
45 }
46
47 int32_t operator -= (const int32_t value) {
48 return android_atomic_add(-value, &value_);
49 }
50
51 int32_t operator |= (const int32_t value) {
52 return android_atomic_or(value, &value_);
53 }
54
55 int32_t operator &= (const int32_t value) {
56 return android_atomic_and(-value, &value_);
57 }
58
Mathieu Chartierd8195f12012-10-05 12:21:28 -070059 int32_t operator ++ (int32_t) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -070060 return android_atomic_inc(&value_);
61 }
62
Mathieu Chartierd8195f12012-10-05 12:21:28 -070063 int32_t operator -- (int32_t) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -070064 return android_atomic_dec(&value_);
65 }
Mathieu Chartier0e4627e2012-10-23 16:13:36 -070066
67 int32_t operator ++ () {
68 return android_atomic_inc(&value_) + 1;
69 }
70
71 int32_t operator -- () {
72 return android_atomic_dec(&value_) - 1;
73 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -070074
75 int CompareAndSwap(int expected_value, int new_value) {
76 return android_atomic_cas(expected_value, new_value, &value_);
77 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -070078 private:
79 int32_t value_;
80};
81
82}
83
84#endif // ART_SRC_ATOMIC_INTEGER_H_