gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/go-grpc-middleware/testing/mutex_readerwriter.go (about) 1 package grpc_testing 2 3 import ( 4 "io" 5 "sync" 6 ) 7 8 // MutexReadWriter is a io.ReadWriter that can be read and worked on from multiple go routines. 9 type MutexReadWriter struct { 10 sync.Mutex 11 rw io.ReadWriter 12 } 13 14 // NewMutexReadWriter creates a new thread-safe io.ReadWriter. 15 func NewMutexReadWriter(rw io.ReadWriter) *MutexReadWriter { 16 return &MutexReadWriter{rw: rw} 17 } 18 19 // Write implements the io.Writer interface. 20 func (m *MutexReadWriter) Write(p []byte) (int, error) { 21 m.Lock() 22 defer m.Unlock() 23 return m.rw.Write(p) 24 } 25 26 // Read implements the io.Reader interface. 27 func (m *MutexReadWriter) Read(p []byte) (int, error) { 28 m.Lock() 29 defer m.Unlock() 30 return m.rw.Read(p) 31 }