forked from fl00r/go-iproto
-
Notifications
You must be signed in to change notification settings - Fork 2
/
parallel_service.go
121 lines (110 loc) · 1.92 KB
/
parallel_service.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package iproto
import (
"log"
"runtime"
"sync"
"time"
)
var _ = log.Print
type BF struct {
N int
Timeout time.Duration
}
func (b BF) New(f func(*Context, *Request) (RetCode, interface{})) (serv *ParallelService) {
if b.N == 0 {
b.N = 1
}
serv = &ParallelService{
SimplePoint: SimplePoint{
Timeout: b.Timeout,
},
f: f,
sema: make(chan struct{}, b.N),
gens: make(generators, b.N),
}
serv.SimplePoint.Init(serv)
for i := 0; i < b.N; i++ {
serv.sema <- struct{}{}
}
Run(serv)
return
}
type ParallelService struct {
SimplePoint
sync.Mutex
f func(*Context, *Request) (RetCode, interface{})
sema chan struct{}
gens generators
}
func (serv *ParallelService) Loop() {
var req *Request
var ok bool
Loop:
for {
select {
case <-serv.ExitChan():
break Loop
default:
select {
case req, ok = <-serv.ReceiveChan():
if !ok {
break Loop
}
default:
select {
case req, ok = <-serv.ReceiveChan():
if !ok {
break Loop
}
case <-serv.ExitChan():
break Loop
}
}
}
select {
case <-serv.ExitChan():
req.ShutDown()
break Loop
default:
select {
case <-serv.sema:
default:
select {
case <-serv.sema:
case <-serv.ExitChan():
req.ShutDown()
break Loop
}
}
}
if ctx := req.Context(); ctx != nil {
ctx.gen = serv.gens.Get()
go serv.serv(ctx)
} else {
serv.sema <- struct{}{}
}
}
for {
if req, ok = <-serv.ReceiveChan(); !ok {
break
}
req.Respond(RcShutdown, nil)
}
}
func (serv *ParallelService) inc(ctx *ReqContext) {
if err := recover(); err != nil {
log.Print(err)
btrace := &[2048]byte{}
n := runtime.Stack(btrace[:], false)
log.Printf("%s", btrace[:n])
}
ctx.Done()
ctx.gen.Release()
serv.sema <- struct{}{}
}
func (serv *ParallelService) serv(ctx *ReqContext) {
defer serv.inc(ctx)
if req := ctx.Request; req != nil {
req.Respond(serv.f(&ctx.Context, req))
}
}