Skip to content

Commit 3e81179

Browse files
committed
Add select nil chan 3
1 parent e7cdb1d commit 3e81179

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

examples/basic/goroutines/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ func (r *register) Regist(m mapping.ExampleMapping) {
2323
m["goroutines_with_context_timeout"] = WithContextTimeout
2424
m["goroutines_select_nil_chan_1"] = SelectNilChan1
2525
m["goroutines_select_nil_chan_2"] = SelectNilChan2
26+
m["goroutines_select_nil_chan_3"] = SelectNilChan3
2627
m["goroutines_using_chan_semaphore"] = UsingChanSemaphore
2728
m["goroutines_using_mutex"] = UsingMutex
2829
m["goroutines_with_context_deadline"] = WithContextDeadline
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package goroutines
2+
3+
import "github.com/devlights/gomy/output"
4+
5+
// SelectNilChan3 -- select ステートメントで nil チャネル を使って選択されるチャネルの有効・無効を切り替えるサンプルです (3).
6+
//
7+
// シンプルな形のサンプル。
8+
func SelectNilChan3() error {
9+
var (
10+
gen = func(out chan<- int) {
11+
defer close(out)
12+
for i := 0; i < 5; i++ {
13+
out <- (i + 1)
14+
}
15+
}
16+
output = func(done chan<- any, in1, in2 <-chan int) {
17+
defer close(done)
18+
19+
LOOP:
20+
for {
21+
select {
22+
case v, ok := <-in1:
23+
if !ok {
24+
in1 = nil
25+
output.Stderrl("[in1]", "close")
26+
continue
27+
}
28+
output.Stderrl("[in1]", v)
29+
case v, ok := <-in2:
30+
if !ok {
31+
in2 = nil
32+
output.Stderrl("[in2]", "close")
33+
continue
34+
}
35+
output.Stderrl("[in2]", v)
36+
default:
37+
if in1 == nil && in2 == nil {
38+
break LOOP
39+
}
40+
}
41+
}
42+
}
43+
)
44+
45+
var (
46+
ch1 = make(chan int)
47+
ch2 = make(chan int)
48+
done = make(chan any)
49+
)
50+
51+
go gen(ch1)
52+
go gen(ch2)
53+
go output(done, ch1, ch2)
54+
55+
<-done
56+
57+
return nil
58+
}

0 commit comments

Comments
 (0)