• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
SoftBusAtomicAdd32(volatile uint32_t * ptr,int32_t value)23 static inline void SoftBusAtomicAdd32(volatile uint32_t* ptr, int32_t value)
24 {
25 #ifdef _WIN32
26     InterlockedExchangeAdd(ptr, value);
27 #elif defined __ICCARM__
28     return;
29 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__
30     __sync_fetch_and_add(ptr, value);
31 #endif
32 }
33 
SoftBusAtomicAddAndFetch32(volatile uint32_t * ptr,int32_t value)34 static inline uint32_t SoftBusAtomicAddAndFetch32(volatile uint32_t* ptr, int32_t value)
35 {
36 #ifdef _WIN32
37     return InterlockedExchangeAdd(ptr, value) + value;
38 #elif defined __ICCARM__
39     return -1;
40 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__
41     return __sync_add_and_fetch(ptr, value);
42 #else
43     return -1;
44 #endif
45 }
46 
SoftBusAtomicAdd64(uint64_t * ptr,int64_t value)47 static inline void SoftBusAtomicAdd64(uint64_t* ptr, int64_t value)
48 {
49 #ifdef _WIN32
50     InterlockedExchangeAdd64((volatile long long*)ptr, value);
51 #elif defined __ICCARM__
52     return;
53 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__
54     __sync_fetch_and_add(ptr, value);
55 #endif
56 }
57 
SoftBusAtomicCmpAndSwap32(volatile uint32_t * ptr,int32_t oldValue,int32_t newValue)58 static inline bool SoftBusAtomicCmpAndSwap32(volatile uint32_t* ptr, int32_t oldValue, int32_t newValue)
59 {
60 #ifdef _WIN32
61     uint32_t initial = InterlockedCompareExchange(ptr, newValue, oldValue);
62     return initial == oldValue;
63 #elif defined __ICCARM__
64     return false;
65 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__
66     return __sync_bool_compare_and_swap(ptr, oldValue, newValue);
67 #else
68     return false;
69 #endif
70 }
71 #endif // SOFTBUS_ADAPTER_ATOMIC_H
72