1 /*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #ifndef SOFTBUS_ADAPTER_ATOMIC_H
17 #define SOFTBUS_ADAPTER_ATOMIC_H
18
19 #include "stdbool.h"
20 #include "stdint.h"
21 #include "stdio.h"
22
23 #ifdef _WIN32
24 #include "intrin.h"
25 #endif
26
SoftBusAtomicAdd32(volatile uint32_t * ptr,int32_t value)27 static inline void SoftBusAtomicAdd32(volatile uint32_t* ptr, int32_t value)
28 {
29 #ifdef _WIN32
30 _InterlockedExchangeAdd(ptr, value);
31 #elif defined __ICCARM__
32 return;
33 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__
34 __sync_fetch_and_add(ptr, value);
35 #endif
36 }
37
SoftBusAtomicAddAndFetch32(volatile uint32_t * ptr,int32_t value)38 static inline uint32_t SoftBusAtomicAddAndFetch32(volatile uint32_t* ptr, int32_t value)
39 {
40 #ifdef _WIN32
41 return _InterlockedExchangeAdd(ptr, value) + value;
42 #elif defined __ICCARM__
43 return -1;
44 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__
45 return __sync_add_and_fetch(ptr, value);
46 #else
47 return -1;
48 #endif
49 }
50
SoftBusAtomicAdd64(uint64_t * ptr,int64_t value)51 static inline void SoftBusAtomicAdd64(uint64_t* ptr, int64_t value)
52 {
53 #ifdef _WIN32
54 _InterlockedExchangeAdd64((volatile long long*)ptr, value);
55 #elif defined __ICCARM__
56 return;
57 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__
58 __sync_fetch_and_add(ptr, value);
59 #endif
60 }
61
SoftBusAtomicCmpAndSwap32(volatile uint32_t * ptr,int32_t oldValue,int32_t newValue)62 static inline bool SoftBusAtomicCmpAndSwap32(volatile uint32_t* ptr, int32_t oldValue, int32_t newValue)
63 {
64 #ifdef _WIN32
65 uint32_t initial = _InterlockedCompareExchange(ptr, newValue, oldValue);
66 return initial == oldValue;
67 #elif defined __ICCARM__
68 return false;
69 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__
70 return __sync_bool_compare_and_swap(ptr, oldValue, newValue);
71 #else
72 return false;
73 #endif
74 }
75 #endif // SOFTBUS_ADAPTER_ATOMIC_H
76