1 // Copyright 2021 The Pigweed Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 4 // use this file except in compliance with the License. You may obtain a copy of 5 // the License at 6 // 7 // https://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, WITHOUT 11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 // License for the specific language governing permissions and limitations under 13 // the License. 14 #pragma once 15 16 #include "pw_rpc/internal/config.h" 17 #include "pw_sync/lock_annotations.h" 18 #include "pw_toolchain/no_destructor.h" 19 20 #if PW_RPC_USE_GLOBAL_MUTEX 21 22 #include "pw_sync/mutex.h" // nogncheck 23 24 #endif // PW_RPC_USE_GLOBAL_MUTEX 25 26 namespace pw::rpc::internal { 27 28 #if PW_RPC_USE_GLOBAL_MUTEX 29 30 using RpcLock = sync::Mutex; 31 32 #else 33 34 class PW_LOCKABLE("pw::rpc::internal::RpcLock") RpcLock { 35 public: 36 constexpr void lock() PW_EXCLUSIVE_LOCK_FUNCTION() {} 37 constexpr void unlock() PW_UNLOCK_FUNCTION() {} 38 }; 39 40 #endif // PW_RPC_USE_GLOBAL_MUTEX 41 rpc_lock()42inline RpcLock& rpc_lock() { 43 static NoDestructor<RpcLock> lock; 44 return *lock; 45 } 46 47 class PW_SCOPED_LOCKABLE RpcLockGuard()48RpcLockGuard{public : RpcLockGuard() 49 PW_EXCLUSIVE_LOCK_FUNCTION(rpc_lock()){rpc_lock().lock(); 50 } // namespace pw::rpc::internal 51 52 ~RpcLockGuard() PW_UNLOCK_FUNCTION(rpc_lock()) { rpc_lock().unlock(); } 53 } 54 ; 55 56 // Releases the RPC lock, yields, and reacquires it. 57 void YieldRpcLock() PW_EXCLUSIVE_LOCKS_REQUIRED(rpc_lock()); 58 59 } // namespace pw::rpc::internal 60