Skip to content

Commit

Permalink
Merge pull request #22 from dferstay/fix-subscriber-close-race
Browse files Browse the repository at this point in the history
Make Subscriber.Close() thread-safe
  • Loading branch information
m110 authored Aug 28, 2024
2 parents 1113f4e + dd5a62b commit 42e837c
Showing 1 changed file with 4 additions and 4 deletions.
8 changes: 4 additions & 4 deletions pkg/kafka/subscriber.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"strings"
"sync"
"sync/atomic"
"time"

"github.com/IBM/sarama"
Expand All @@ -21,7 +22,7 @@ type Subscriber struct {
closing chan struct{}
subscribersWg sync.WaitGroup

closed bool
closed uint32
}

// NewSubscriber creates a new Kafka Subscriber.
Expand Down Expand Up @@ -137,7 +138,7 @@ func DefaultSaramaSubscriberConfig() *sarama.Config {
//
// There are multiple subscribers spawned
func (s *Subscriber) Subscribe(ctx context.Context, topic string) (<-chan *message.Message, error) {
if s.closed {
if atomic.LoadUint32(&s.closed) == 1 {
return nil, errors.New("subscriber closed")
}

Expand Down Expand Up @@ -474,11 +475,10 @@ func (s *Subscriber) createMessagesHandler(output chan *message.Message) message
}

func (s *Subscriber) Close() error {
if s.closed {
if !atomic.CompareAndSwapUint32(&s.closed, 0, 1) {
return nil
}

s.closed = true
close(s.closing)
s.subscribersWg.Wait()

Expand Down

0 comments on commit 42e837c

Please sign in to comment.