Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix race condition by adding a mutex for deadline access #41

Merged
merged 1 commit into from
Apr 5, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,9 @@ type Stream struct {
// for later memory pool freeing
exbuf []byte

wDeadline time.Time
rDeadline time.Time
deadlineLock sync.Mutex
wDeadline time.Time
rDeadline time.Time

clLock sync.Mutex
closedRemote bool
Expand All @@ -57,11 +58,13 @@ func (s *Stream) Name() string {
}

func (s *Stream) waitForData(ctx context.Context) error {
s.deadlineLock.Lock()
if !s.rDeadline.IsZero() {
dctx, cancel := context.WithDeadline(ctx, s.rDeadline)
defer cancel()
ctx = dctx
}
s.deadlineLock.Unlock()

select {
case <-s.reset:
Expand Down Expand Up @@ -146,13 +149,15 @@ func (s *Stream) write(b []byte) (int, error) {
return 0, errors.New("cannot write to closed stream")
}

s.deadlineLock.Lock()
wDeadlineCtx, cleanup := func(s *Stream) (context.Context, context.CancelFunc) {
if s.wDeadline.IsZero() {
return s.closedLocal, nil
} else {
return context.WithDeadline(s.closedLocal, s.wDeadline)
}
}(s)
s.deadlineLock.Unlock()

err := s.mp.sendMsg(wDeadlineCtx, s.id.header(messageTag), b)

Expand Down Expand Up @@ -224,17 +229,23 @@ func (s *Stream) Reset() error {
}

func (s *Stream) SetDeadline(t time.Time) error {
s.deadlineLock.Lock()
defer s.deadlineLock.Unlock()
s.rDeadline = t
s.wDeadline = t
return nil
}

func (s *Stream) SetReadDeadline(t time.Time) error {
s.deadlineLock.Lock()
defer s.deadlineLock.Unlock()
s.rDeadline = t
return nil
}

func (s *Stream) SetWriteDeadline(t time.Time) error {
s.deadlineLock.Lock()
defer s.deadlineLock.Unlock()
s.wDeadline = t
return nil
}