1 /*
2 * Copyright (c) 2020-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 GRAPHIC_LITE_HAL_ATOMIC_H
17 #define GRAPHIC_LITE_HAL_ATOMIC_H
18
19 #include "stdbool.h"
20 #include "stdint.h"
21 #include "stdio.h"
22
HalAtomicAdd32(volatile uint32_t * ptr,uint32_t value)23 static inline void HalAtomicAdd32(volatile uint32_t* ptr, uint32_t value)
24 {
25 #ifdef _WIN32
26 InterlockedExchangeAdd(ptr, value);
27 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__
28 __sync_fetch_and_add(ptr, value);
29 #endif
30 }
31
HalAtomicAddAndFetch32(volatile uint32_t * ptr,uint32_t value)32 static inline uint32_t HalAtomicAddAndFetch32(volatile uint32_t* ptr, uint32_t value)
33 {
34 #ifdef _WIN32
35 return InterlockedExchangeAdd(ptr, value) + value;
36 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__
37 return __sync_add_and_fetch(ptr, value);
38 #else
39 return -1;
40 #endif
41 }
42
HalAtomicAdd64(uint64_t * ptr,uint64_t value)43 static inline void HalAtomicAdd64(uint64_t* ptr, uint64_t value)
44 {
45 #ifdef _WIN32
46 InterlockedExchangeAdd64((volatile long long*)ptr, value);
47 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__
48 __sync_fetch_and_add(ptr, value);
49 #endif
50 }
51
HalAtomicCmpAndSwap32(volatile uint32_t * ptr,uint32_t oldValue,uint32_t newValue)52 static inline bool HalAtomicCmpAndSwap32(volatile uint32_t* ptr, uint32_t oldValue, uint32_t newValue)
53 {
54 #ifdef _WIN32
55 uint32_t initial = InterlockedCompareExchange(ptr, newValue, oldValue);
56 return initial == oldValue;
57 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__
58 return __sync_bool_compare_and_swap(ptr, oldValue, newValue);
59 #else
60 return false;
61 #endif
62 }
63 #endif // GRAPHIC_LITE_HAL_ATOMIC_H
64