github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/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  }