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 SPINLOCK_H 17#define SPINLOCK_H 18 19typedef struct { 20 volatile int lock; 21} Spinlock; 22 23 24#if defined(__x86_64__) 25#include <emmintrin.h> 26 27inline static void Pause(void) 28{ 29 _mm_pause(); 30} 31#elif defined(RTP_ARCH_ARM) 32static inline void Pause(void) 33{ 34 asm volatile("yield" ::: "memory"); 35} 36#else 37static inline void Pause(void) 38{ 39} 40#endif 41 42static inline void SpinLockInit(Spinlock *spinlock) 43{ 44 spinlock->lock = 0; 45} 46 47static inline int SpinLockTryLock(Spinlock *spinlock) 48{ 49 if (__sync_bool_compare_and_swap(&spinlock->lock, 0, 1) == 0) { 50 return 0; 51 } 52 53 return 1; 54} 55 56static inline void SpinLock(Spinlock *spinlock) 57{ 58 while (!SpinLockTryLock(spinlock)) { 59 do { 60 Pause(); 61 } while (!!spinlock->lock); 62 } 63} 64 65static inline void SpinUnlock(Spinlock *spinlock) 66{ 67 __sync_lock_release(&spinlock->lock); 68} 69 70#endif /* SPINLOCK_H */ 71 72