-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTaskChannel.go
54 lines (44 loc) · 918 Bytes
/
TaskChannel.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
package executors
import (
"fmt"
"sync"
)
type taskChannel chan Task
type taskChannelHolder struct {
channel taskChannel
wg sync.WaitGroup
}
type errorCallback func(interface{})
func callSafely(task Task, handleError errorCallback) {
defer func() {
if val := recover(); val != nil {
handleError(val)
}
}()
task()
}
var DefaultCallback = func(panicVal interface{}) {
fmt.Println("Last defence error:", panicVal)
}
func makeNewChannel(capacity int) (channel taskChannel) {
channel = make(taskChannel, capacity)
return
}
func consumeTasks(channel taskChannel, wg *sync.WaitGroup) {
defer wg.Done()
for {
if task := <-channel; task != nil {
callSafely(task, DefaultCallback)
} else {
//shutdown on channel
break
}
}
}
func (ste *taskChannelHolder) Execute(task Task) {
ste.channel <- task
}
func (ste *taskChannelHolder) Shutdown() {
close(ste.channel)
ste.wg.Wait()
}