-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker-pool.go
81 lines (67 loc) · 1.82 KB
/
worker-pool.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// see LICENSE file
package spool
import (
"context"
"log"
"github.com/dc0d/actor"
)
type WorkerPool chan func()
// New creates a new WorkerPool without any initial workers. To spawn workers, Grow must be called.
func New(mailboxSize MailboxSize) WorkerPool {
if mailboxSize < 0 {
mailboxSize = 0
}
return make(chan func(), mailboxSize)
}
func (pool WorkerPool) Stop() {
close(pool)
}
// Blocking will panic, if the workerpool is stopped.
func (pool WorkerPool) Blocking(ctx context.Context, callback func()) error {
done := make(chan struct{})
select {
case <-ctx.Done():
return ctx.Err()
case pool <- func() { defer close(done); callback() }:
}
<-done
return nil
}
// SemiBlocking sends the job to the worker in a non-blocking manner, as long as the mailbox is not full.
// After that, it becomes blocking until there is an empty space in the mailbox.
// If the workerpool is stopped, SemiBlocking will panic.
func (pool WorkerPool) SemiBlocking(ctx context.Context, callback func()) error {
select {
case <-ctx.Done():
return ctx.Err()
case pool <- callback:
}
return nil
}
func (pool WorkerPool) Grow(ctx context.Context, growth int, options ...actor.Option) {
pool.grow(ctx, growth, nil, options...)
}
func (pool WorkerPool) grow(ctx context.Context, growth int, executorFactory func() actor.Callbacks[T], options ...actor.Option) {
var mailbox <-chan func() = pool
for i := 0; i < growth; i++ {
var exec actor.Callbacks[T] = defaultExecutor{}
if executorFactory != nil {
exec = executorFactory()
}
actor.Start(ctx, mailbox, exec, options...)
}
}
type defaultExecutor struct{}
func (obj defaultExecutor) Received(fn T) {
defer func() {
if e := recover(); e != nil {
log.Println(e) // TODO:
}
}()
fn()
}
func (obj defaultExecutor) Stopped() {}
type (
T = func()
MailboxSize int
)