1 /* 2 * Copyright 2022 Meta 3 * 4 * SPDX-License-Identifier: Apache-2.0 5 */ 6 7 #include <zephyr/kernel.h> 8 9 #include <thrift/concurrency/Mutex.h> 10 11 namespace apache 12 { 13 namespace thrift 14 { 15 namespace concurrency 16 { 17 18 class Mutex::impl 19 { 20 public: 21 k_spinlock_key_t key; 22 struct k_spinlock lock; 23 }; 24 Mutex()25Mutex::Mutex() 26 { 27 impl_ = std::make_shared<Mutex::impl>(); 28 } 29 lock() const30void Mutex::lock() const 31 { 32 while (!trylock()) { 33 k_msleep(1); 34 } 35 } 36 trylock() const37bool Mutex::trylock() const 38 { 39 return k_spin_trylock(&impl_->lock, &impl_->key) == 0; 40 } 41 timedlock(int64_t milliseconds) const42bool Mutex::timedlock(int64_t milliseconds) const 43 { 44 k_timepoint_t end = sys_timepoint_calc(K_MSEC(milliseconds)); 45 46 do { 47 if (trylock()) { 48 return true; 49 } 50 k_msleep(5); 51 } while(!sys_timepoint_expired(end)); 52 53 return false; 54 } 55 unlock() const56void Mutex::unlock() const 57 { 58 k_spin_unlock(&impl_->lock, impl_->key); 59 } 60 getUnderlyingImpl() const61void *Mutex::getUnderlyingImpl() const 62 { 63 return &impl_->lock; 64 } 65 } // namespace concurrency 66 } // namespace thrift 67 } // namespace apache 68