Home | History | Annotate | Download | only in runtime
      1 /*
      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_RUNTIME_ATOMIC_INTEGER_H_
     18 #define ART_RUNTIME_ATOMIC_INTEGER_H_
     19 
     20 #include "cutils/atomic.h"
     21 #include "cutils/atomic-inline.h"
     22 
     23 namespace art {
     24 
     25 class AtomicInteger {
     26  public:
     27   AtomicInteger() : value_(0) { }
     28 
     29   explicit AtomicInteger(int32_t value) : value_(value) { }
     30 
     31   // Unsafe = operator for non atomic operations on the integer.
     32   void store(int32_t desired) {
     33     value_ = desired;
     34   }
     35 
     36   AtomicInteger& operator=(int32_t desired) {
     37     store(desired);
     38     return *this;
     39   }
     40 
     41   int32_t load() const {
     42     return value_;
     43   }
     44 
     45   operator int32_t() const {
     46     return load();
     47   }
     48 
     49   int32_t fetch_add(const int32_t value) {
     50     return android_atomic_add(value, &value_);
     51   }
     52 
     53   int32_t fetch_sub(const int32_t value) {
     54     return android_atomic_add(-value, &value_);
     55   }
     56 
     57   int32_t operator++() {
     58     return android_atomic_inc(&value_) + 1;
     59   }
     60 
     61   int32_t operator++(int32_t) {
     62     return android_atomic_inc(&value_);
     63   }
     64 
     65   int32_t operator--() {
     66     return android_atomic_dec(&value_) - 1;
     67   }
     68 
     69   int32_t operator--(int32_t) {
     70     return android_atomic_dec(&value_);
     71   }
     72 
     73   bool compare_and_swap(int32_t expected_value, int32_t desired_value) {
     74     return android_atomic_cas(expected_value, desired_value, &value_) == 0;
     75   }
     76 
     77  private:
     78   volatile int32_t value_;
     79 };
     80 
     81 }  // namespace art
     82 
     83 #endif  // ART_RUNTIME_ATOMIC_INTEGER_H_
     84