Skip to content

Commit 71fc45c

Browse files
authored
Merge pull request #667 from devlights:add-helloworld-async3
Add helloworld_async3
2 parents 64da0e0 + 96d6b48 commit 71fc45c

File tree

3 files changed

+97
-0
lines changed

3 files changed

+97
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
}

examples/basic/helloworld/examples.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package helloworld
22

33
import (
44
"github.com/devlights/try-golang/examples/basic/helloworld/async2"
5+
"github.com/devlights/try-golang/examples/basic/helloworld/async3"
56
"github.com/devlights/try-golang/mapping"
67
)
78

@@ -19,5 +20,6 @@ func (r *register) Regist(m mapping.ExampleMapping) {
1920
m["helloworld_sync"] = Sync
2021
m["helloworld_async"] = Async
2122
m["helloworld_async2"] = async2.Async2
23+
m["helloworld_async3"] = async3.Async3
2224
m["helloworld_mixed"] = Mixed
2325
}

0 commit comments

Comments
 (0)