Skip to content

Commit 8eb698d

Browse files
committed
Add loops.InfiniteLoop
1 parent 2ec3c7c commit 8eb698d

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

examples/basic/loops/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,5 @@ func (r *register) Regist(m mapping.ExampleMapping) {
1818
m["loops_channel_loop"] = ChannelLoop
1919
m["loops_map_loop"] = MapLoop
2020
m["loops_range_loop"] = RangeLoop
21+
m["loops_infinite_loop"] = InfiniteLoop
2122
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package loops
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"time"
7+
)
8+
9+
// InfiniteLoop は、無限ループのサンプルです.
10+
func InfiniteLoop() error {
11+
var (
12+
mainCtx, mainCxl = context.WithCancel(context.Background())
13+
procCtx, procCxl = context.WithTimeout(mainCtx, 3*time.Second)
14+
)
15+
16+
defer mainCxl()
17+
defer procCxl()
18+
19+
// Go では 無限ループ は以下のように for {} とだけ書く
20+
LOOP:
21+
for {
22+
select {
23+
case <-time.After(200 * time.Millisecond):
24+
fmt.Print(".")
25+
case <-procCtx.Done():
26+
break LOOP
27+
}
28+
}
29+
30+
fmt.Println("")
31+
32+
return nil
33+
}

0 commit comments

Comments
 (0)