Skip to content

Commit

Permalink
Use atomic bool instead of mutex (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
nrwiersma authored Jul 5, 2018
1 parent ff8a651 commit 27d4006
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 30 deletions.
8 changes: 7 additions & 1 deletion Gopkg.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions Gopkg.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
name = "github.com/bsm/sarama-cluster"
version = "2.*"

[[constraint]]
branch = "master"
name = "github.com/tevino/abool"

[[constraint]]
name = "github.com/stretchr/testify"
version = "1.*"
Expand Down
44 changes: 15 additions & 29 deletions task.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package streams

import (
"sync"

"github.com/tevino/abool"
)

type nodeMessage struct {
Expand All @@ -18,11 +20,9 @@ type Task interface {
}

type streamTask struct {
sync.RWMutex

topology *Topology

running bool
running *abool.AtomicBool
errorFn ErrorFunc
stream chan nodeMessage
runWg sync.WaitGroup
Expand All @@ -32,27 +32,22 @@ type streamTask struct {
func NewTask(topology *Topology) Task {
return &streamTask{
topology: topology,
running: false,
running: abool.New(),
}
}

func (t *streamTask) run() {
// If we are already running, exit
if t.isRunning() {
return
}
t.runWg.Add(1)
defer t.runWg.Done()

t.stream = make(chan nodeMessage, 1000)
t.setRunning(true)
t.running.Set()

ctx := NewProcessorPipe()
t.setupTopology(ctx)

t.consumeSources()

t.runWg.Add(1)
defer t.runWg.Done()

for r := range t.stream {
ctx.SetNode(r.node)
if err := r.node.Process(r.msg); err != nil {
Expand Down Expand Up @@ -84,7 +79,7 @@ func (t *streamTask) closeTopology() error {
}

func (t *streamTask) handleError(err error) {
t.setRunning(false)
t.running.UnSet()

t.errorFn(err)
}
Expand All @@ -95,7 +90,7 @@ func (t *streamTask) consumeSources() {
t.sourceWg.Add(1)
defer t.sourceWg.Done()

for t.isRunning() {
for t.running.IsSet() {
msg, err := source.Consume()
if err != nil {
t.handleError(err)
Expand All @@ -114,21 +109,12 @@ func (t *streamTask) consumeSources() {
}
}

func (t *streamTask) isRunning() bool {
t.RLock()
running := t.running
t.RUnlock()

return running
}

func (t *streamTask) setRunning(running bool) {
t.Lock()
t.running = running
t.Unlock()
}

func (t *streamTask) Start() {
// If we are already running, exit
if t.running.IsSet() {
return
}

go t.run()
}

Expand All @@ -137,7 +123,7 @@ func (t *streamTask) OnError(fn ErrorFunc) {
}

func (t *streamTask) Close() error {
t.setRunning(false)
t.running.UnSet()
t.sourceWg.Wait()

close(t.stream)
Expand Down

0 comments on commit 27d4006

Please sign in to comment.