From 5cd7f324f964e99f4f6aa4e0e54e9834e88fd2d3 Mon Sep 17 00:00:00 2001 From: Taizeng Wu Date: Wed, 5 Dec 2018 16:30:09 +0800 Subject: [PATCH] Use channel to implement a simple way to wait --- client.go | 3 +-- conn.go | 16 +++++----------- 2 files changed, 6 insertions(+), 13 deletions(-) diff --git a/client.go b/client.go index 5ceb06c..ef885d8 100644 --- a/client.go +++ b/client.go @@ -6,7 +6,6 @@ import ( "io" "os" "path" - "sync" "sync/atomic" "syscall" "time" @@ -123,7 +122,7 @@ func NewClientPipe(rd io.Reader, wr io.WriteCloser, opts ...ClientOption) (*Clie WriteCloser: wr, }, inflight: make(map[uint32]chan<- result), - errCond: sync.NewCond(new(sync.Mutex)), + closed: make(chan struct{}), }, maxPacket: 1 << 15, maxConcurrentRequests: 64, diff --git a/conn.go b/conn.go index bfb0a8b..62e585e 100644 --- a/conn.go +++ b/conn.go @@ -37,19 +37,15 @@ type clientConn struct { sync.Mutex // protects inflight inflight map[uint32]chan<- result // outstanding requests - errCond *sync.Cond - err error + closed chan struct{} + err error } // Wait blocks until the conn has shut down, and return the error // causing the shutdown. It can be called concurrently from multiple // goroutines. func (c *clientConn) Wait() error { - c.errCond.L.Lock() - defer c.errCond.L.Unlock() - for c.err == nil { - c.errCond.Wait() - } + <-c.closed return c.err } @@ -64,10 +60,6 @@ func (c *clientConn) loop() { err := c.recv() if err != nil { c.broadcastErr(err) - c.errCond.L.Lock() - c.err = err - c.errCond.Broadcast() - c.errCond.L.Unlock() } } @@ -141,6 +133,8 @@ func (c *clientConn) broadcastErr(err error) { for _, ch := range listeners { ch <- result{err: err} } + c.err = err + close(c.closed) } type serverConn struct {