blob: 31cdd859f0b25cb74cef7208b46274dd1dade894 [file] [log] [blame]
bigbiff7abc5fe2015-01-17 16:53:12 -05001/*
2 * Copyright (C) 2015 The Team Win Recovery 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#include <pthread.h>
18#include <stdio.h>
19#include "tw_atomic.hpp"
20
21/*
22 * According to this documentation:
23 * https://developer.android.com/training/articles/smp.html
24 * it is recommended to use mutexes instead of atomics. This class
25 * provides us with a wrapper to make "atomic" variables easy to use.
26 */
27
28TWAtomicInt::TWAtomicInt(int initial_value /* = 0 */) {
29 if (pthread_mutex_init(&mutex_lock, NULL) != 0) {
30 // This should hopefully never happen. If it does, the
31 // operations will not be atomic, but we will allow things to
32 // continue anyway after logging the issue and just hope for
33 // the best.
34 printf("TWAtomic error initializing mutex.\n");
35 use_mutex = false;
36 } else {
37 use_mutex = true;
38 }
39 value = initial_value;
40}
41
42TWAtomicInt::~TWAtomicInt() {
43 if (use_mutex)
44 pthread_mutex_destroy(&mutex_lock);
45}
46
47void TWAtomicInt::set_value(int new_value) {
48 if (use_mutex) {
49 pthread_mutex_lock(&mutex_lock);
50 value = new_value;
51 pthread_mutex_unlock(&mutex_lock);
52 } else {
53 value = new_value;
54 }
55}
56
57int TWAtomicInt::get_value(void) {
58 int ret_val;
59
60 if (use_mutex) {
61 pthread_mutex_lock(&mutex_lock);
62 ret_val = value;
63 pthread_mutex_unlock(&mutex_lock);
64 } else {
65 ret_val = value;
66 }
67 return ret_val;
68}