Skip to content

Commit

Permalink
feat: add WorkerTaskQueue#WaitForNoActiveTasks() for tests (#284)
Browse files Browse the repository at this point in the history
* feat: add WorkerTaskQueue#WaitForNoActiveTasks() for tests

* fixup! feat: add WorkerTaskQueue#WaitForNoActiveTasks() for tests
  • Loading branch information
rvagg authored and hannahhoward committed Dec 1, 2021
1 parent 2925810 commit ba823ac
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions taskqueue/taskqueue.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package taskqueue

import (
"context"
"sync/atomic"
"time"

"github.com/ipfs/go-peertaskqueue"
Expand Down Expand Up @@ -32,7 +33,9 @@ type WorkerTaskQueue struct {
cancelFn func()
peerTaskQueue *peertaskqueue.PeerTaskQueue
workSignal chan struct{}
noTaskSignal chan struct{}
ticker *time.Ticker
activeTasks int32
}

// NewTaskQueue initializes a new queue
Expand All @@ -43,6 +46,7 @@ func NewTaskQueue(ctx context.Context) *WorkerTaskQueue {
cancelFn: cancelFn,
peerTaskQueue: peertaskqueue.New(),
workSignal: make(chan struct{}, 1),
noTaskSignal: make(chan struct{}, 1),
ticker: time.NewTicker(thawSpeed),
}
}
Expand Down Expand Up @@ -88,6 +92,16 @@ func (tq *WorkerTaskQueue) Shutdown() {
tq.cancelFn()
}

func (tq *WorkerTaskQueue) WaitForNoActiveTasks() {
for atomic.LoadInt32(&tq.activeTasks) > 0 {
select {
case <-tq.ctx.Done():
return
case <-tq.noTaskSignal:
}
}
}

func (tq *WorkerTaskQueue) worker(executor Executor) {
targetWork := 1
for {
Expand All @@ -104,7 +118,14 @@ func (tq *WorkerTaskQueue) worker(executor Executor) {
}
}
for _, task := range tasks {
atomic.AddInt32(&tq.activeTasks, 1)
terminate := executor.ExecuteTask(tq.ctx, pid, task)
if atomic.AddInt32(&tq.activeTasks, -1) == 0 {
select {
case tq.noTaskSignal <- struct{}{}:
default:
}
}
if terminate {
return
}
Expand Down

0 comments on commit ba823ac

Please sign in to comment.