File tree Expand file tree Collapse file tree 3 files changed +97
-0
lines changed
examples/basic/helloworld Expand file tree Collapse file tree 3 files changed +97
-0
lines changed Original file line number Diff line number Diff line change
1
+ package async3
2
+
3
+ import (
4
+ "log"
5
+ "math/rand"
6
+ "time"
7
+ )
8
+
9
+ var (
10
+ count = 20
11
+ delay = func () time.Duration {
12
+ return time .Duration (rand .Intn (200 )) * time .Millisecond
13
+ }
14
+ )
15
+
16
+ // Async3 -- HelloWorld 非同期版 (3)
17
+ func Async3 () error {
18
+ log .SetFlags (0 )
19
+
20
+ var (
21
+ hello = newRunner ("hello" , count , delay )
22
+ world = newRunner ("world" , count , delay )
23
+ )
24
+
25
+ hello .run ()
26
+ world .run ()
27
+
28
+ var (
29
+ h string
30
+ w string
31
+ hOk = true
32
+ wOk = true
33
+ )
34
+
35
+ for {
36
+ select {
37
+ case h , hOk = <- hello .ch :
38
+ if ! hOk {
39
+ break
40
+ }
41
+ log .Println (h )
42
+ case w , wOk = <- world .ch :
43
+ if ! wOk {
44
+ break
45
+ }
46
+ log .Println (w )
47
+ }
48
+
49
+ if ! hOk && ! wOk {
50
+ break
51
+ }
52
+ }
53
+
54
+ return nil
55
+ }
Original file line number Diff line number Diff line change
1
+ package async3
2
+
3
+ import (
4
+ "fmt"
5
+ "time"
6
+ )
7
+
8
+ type _runner struct {
9
+ name string
10
+ ch chan string
11
+ count int
12
+ delay func () time.Duration
13
+ }
14
+
15
+ func newRunner (name string , count int , delay func () time.Duration ) * _runner {
16
+ r := new (_runner )
17
+
18
+ r .name = name
19
+ r .ch = make (chan string )
20
+ r .count = count
21
+ r .delay = delay
22
+
23
+ return r
24
+ }
25
+
26
+ func (me * _runner ) run () {
27
+ go func () {
28
+ defer close (me .ch )
29
+
30
+ for i := 0 ; i < me .count ; i ++ {
31
+ d := me .delay ()
32
+ time .Sleep (d )
33
+ me .ch <- fmt .Sprintf ("%d:%s (%v)" , i , me , d )
34
+ }
35
+ }()
36
+ }
37
+
38
+ func (me * _runner ) String () string {
39
+ return me .name
40
+ }
Original file line number Diff line number Diff line change @@ -2,6 +2,7 @@ package helloworld
2
2
3
3
import (
4
4
"github.com/devlights/try-golang/examples/basic/helloworld/async2"
5
+ "github.com/devlights/try-golang/examples/basic/helloworld/async3"
5
6
"github.com/devlights/try-golang/mapping"
6
7
)
7
8
@@ -19,5 +20,6 @@ func (r *register) Regist(m mapping.ExampleMapping) {
19
20
m ["helloworld_sync" ] = Sync
20
21
m ["helloworld_async" ] = Async
21
22
m ["helloworld_async2" ] = async2 .Async2
23
+ m ["helloworld_async3" ] = async3 .Async3
22
24
m ["helloworld_mixed" ] = Mixed
23
25
}
You can’t perform that action at this time.
0 commit comments