-
Notifications
You must be signed in to change notification settings - Fork 283
/
Copy pathtasker.go
45 lines (40 loc) · 880 Bytes
/
tasker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package tasker
// Tasker is a small helper utility that makes it easy to move tasks to a
// different goroutine. This is useful when some work must be executed from a
// specific goroutine / OS thread.
type Tasker struct {
taskCh chan task
}
type task struct {
f func()
doneCh chan struct{}
}
// New prepares a new Tasker.
func New() *Tasker {
t := &Tasker{
taskCh: make(chan task),
}
return t
}
// Do runs the given function in the goroutine where ExecuteTasks is called. Do
// blocks until the given function has completed.
func (t *Tasker) Do(f func()) {
doneCh := make(chan struct{})
t.taskCh <- task{
f: f,
doneCh: doneCh,
}
<-doneCh
}
// ExecuteTasks executes any pending tasks, then returns.
func (t *Tasker) ExecuteTasks() {
for {
select {
case task := <-t.taskCh:
task.f()
task.doneCh <- struct{}{}
default:
return
}
}
}