trpc.group/trpc-go/trpc-go@v1.0.3/transport/tnet/multiplex/statemutex.go (about) 1 // 2 // 3 // Tencent is pleased to support the open source community by making tRPC available. 4 // 5 // Copyright (C) 2023 THL A29 Limited, a Tencent company. 6 // All rights reserved. 7 // 8 // If you have downloaded a copy of the tRPC source code from Tencent, 9 // please note that tRPC source code is licensed under the Apache 2.0 License, 10 // A copy of the Apache 2.0 License is included in this file. 11 // 12 // 13 14 //go:build linux || freebsd || dragonfly || darwin 15 // +build linux freebsd dragonfly darwin 16 17 package multiplex 18 19 import ( 20 "sync" 21 ) 22 23 // stateRWMutex is similar to sync.RWMutex, but it has a closed state. 24 type stateRWMutex struct { 25 mu sync.RWMutex 26 isClosed bool 27 } 28 29 // rLock locks rw for reading, returns false if mutex is closed. 30 func (rw *stateRWMutex) rLock() bool { 31 rw.mu.RLock() 32 if rw.isClosed { 33 rw.mu.RUnlock() 34 return false 35 } 36 return true 37 } 38 39 // rUnlock unlocks rw for reading. 40 func (rw *stateRWMutex) rUnlock() { 41 rw.mu.RUnlock() 42 } 43 44 // lock locks rw for writing, returns false if mutex is closed. 45 func (rw *stateRWMutex) lock() bool { 46 rw.mu.Lock() 47 if rw.isClosed { 48 rw.mu.Unlock() 49 return false 50 } 51 return true 52 } 53 54 // unlock unlocks rw for writing. 55 func (rw *stateRWMutex) unlock() { 56 rw.mu.Unlock() 57 } 58 59 // closeLocked closes the mutex. It should be called only after stateRWMutex.lock. 60 func (rw *stateRWMutex) closeLocked() { 61 rw.isClosed = true 62 }