Skip to content

Commit ba823ac

Browse files
rvagghannahhoward
authored andcommitted
feat: add WorkerTaskQueue#WaitForNoActiveTasks() for tests (#284)
* feat: add WorkerTaskQueue#WaitForNoActiveTasks() for tests * fixup! feat: add WorkerTaskQueue#WaitForNoActiveTasks() for tests
1 parent 2925810 commit ba823ac

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

taskqueue/taskqueue.go

+21
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package taskqueue
22

33
import (
44
"context"
5+
"sync/atomic"
56
"time"
67

78
"github.com/ipfs/go-peertaskqueue"
@@ -32,7 +33,9 @@ type WorkerTaskQueue struct {
3233
cancelFn func()
3334
peerTaskQueue *peertaskqueue.PeerTaskQueue
3435
workSignal chan struct{}
36+
noTaskSignal chan struct{}
3537
ticker *time.Ticker
38+
activeTasks int32
3639
}
3740

3841
// NewTaskQueue initializes a new queue
@@ -43,6 +46,7 @@ func NewTaskQueue(ctx context.Context) *WorkerTaskQueue {
4346
cancelFn: cancelFn,
4447
peerTaskQueue: peertaskqueue.New(),
4548
workSignal: make(chan struct{}, 1),
49+
noTaskSignal: make(chan struct{}, 1),
4650
ticker: time.NewTicker(thawSpeed),
4751
}
4852
}
@@ -88,6 +92,16 @@ func (tq *WorkerTaskQueue) Shutdown() {
8892
tq.cancelFn()
8993
}
9094

95+
func (tq *WorkerTaskQueue) WaitForNoActiveTasks() {
96+
for atomic.LoadInt32(&tq.activeTasks) > 0 {
97+
select {
98+
case <-tq.ctx.Done():
99+
return
100+
case <-tq.noTaskSignal:
101+
}
102+
}
103+
}
104+
91105
func (tq *WorkerTaskQueue) worker(executor Executor) {
92106
targetWork := 1
93107
for {
@@ -104,7 +118,14 @@ func (tq *WorkerTaskQueue) worker(executor Executor) {
104118
}
105119
}
106120
for _, task := range tasks {
121+
atomic.AddInt32(&tq.activeTasks, 1)
107122
terminate := executor.ExecuteTask(tq.ctx, pid, task)
123+
if atomic.AddInt32(&tq.activeTasks, -1) == 0 {
124+
select {
125+
case tq.noTaskSignal <- struct{}{}:
126+
default:
127+
}
128+
}
108129
if terminate {
109130
return
110131
}

0 commit comments

Comments
 (0)