Skip to content
This repository has been archived by the owner on May 26, 2022. It is now read-only.

Commit

Permalink
Merge pull request #85 from libp2p/fix/deadline-race
Browse files Browse the repository at this point in the history
fix: add read/write locks
  • Loading branch information
Stebalien committed Apr 22, 2020
2 parents b2d49c9 + f7e5cea commit 2c77fd7
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions conn_native.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,14 @@ type Conn struct {
DefaultMessageType int
reader io.Reader
closeOnce sync.Once

readLock, writeLock sync.Mutex
}

func (c *Conn) Read(b []byte) (int, error) {
c.readLock.Lock()
defer c.readLock.Unlock()

if c.reader == nil {
if err := c.prepNextReader(); err != nil {
return 0, err
Expand Down Expand Up @@ -67,6 +72,9 @@ func (c *Conn) prepNextReader() error {
}

func (c *Conn) Write(b []byte) (n int, err error) {
c.writeLock.Lock()
defer c.writeLock.Unlock()

if err := c.Conn.WriteMessage(c.DefaultMessageType, b); err != nil {
return 0, err
}
Expand Down Expand Up @@ -113,10 +121,18 @@ func (c *Conn) SetDeadline(t time.Time) error {
}

func (c *Conn) SetReadDeadline(t time.Time) error {
// Don't lock when setting the read deadline. That would prevent us from
// interrupting an in-progress read.
return c.Conn.SetReadDeadline(t)
}

func (c *Conn) SetWriteDeadline(t time.Time) error {
// Unlike the read deadline, we need to lock when setting the write
// deadline.

c.writeLock.Lock()
defer c.writeLock.Unlock()

return c.Conn.SetWriteDeadline(t)
}

Expand Down

0 comments on commit 2c77fd7

Please sign in to comment.