forked from name5566/leaf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
127 lines (102 loc) · 1.78 KB
/
example_test.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
122
123
124
125
126
127
package chanrpc_test
import (
"fmt"
"github.com/rivest829/leaf/chanrpc"
"sync"
)
func Example() {
s := chanrpc.NewServer(10)
var wg sync.WaitGroup
wg.Add(1)
// goroutine 1
go func() {
s.Register("f0", func(args []interface{}) {
})
s.Register("f1", func(args []interface{}) interface{} {
return 1
})
s.Register("fn", func(args []interface{}) []interface{} {
return []interface{}{1, 2, 3}
})
s.Register("add", func(args []interface{}) interface{} {
n1 := args[0].(int)
n2 := args[1].(int)
return n1 + n2
})
wg.Done()
for {
s.Exec(<-s.ChanCall)
}
}()
wg.Wait()
wg.Add(1)
// goroutine 2
go func() {
c := s.Open(10)
// sync
err := c.Call0("f0")
if err != nil {
fmt.Println(err)
}
r1, err := c.Call1("f1")
if err != nil {
fmt.Println(err)
} else {
fmt.Println(r1)
}
rn, err := c.CallN("fn")
if err != nil {
fmt.Println(err)
} else {
fmt.Println(rn[0], rn[1], rn[2])
}
ra, err := c.Call1("add", 1, 2)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(ra)
}
// asyn
c.AsynCall("f0", func(err error) {
if err != nil {
fmt.Println(err)
}
})
c.AsynCall("f1", func(ret interface{}, err error) {
if err != nil {
fmt.Println(err)
} else {
fmt.Println(ret)
}
})
c.AsynCall("fn", func(ret []interface{}, err error) {
if err != nil {
fmt.Println(err)
} else {
fmt.Println(ret[0], ret[1], ret[2])
}
})
c.AsynCall("add", 1, 2, func(ret interface{}, err error) {
if err != nil {
fmt.Println(err)
} else {
fmt.Println(ret)
}
})
c.Cb(<-c.ChanAsynRet)
c.Cb(<-c.ChanAsynRet)
c.Cb(<-c.ChanAsynRet)
c.Cb(<-c.ChanAsynRet)
// go
s.Go("f0")
wg.Done()
}()
wg.Wait()
// Output:
// 1
// 1 2 3
// 3
// 1
// 1 2 3
// 3
}