select

select

 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
package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	ch1 := make(chan int)
	ch2 := make(chan int)

	waitSeconds := 2

	go func() {
		t := time.After(time.Duration(waitSeconds) * time.Second)
		for {
			select {
			case ch1 <- rand.Intn(101):
				time.Sleep(time.Second)
			case <-t:
				fmt.Println("1 time out")
				close(ch1)
				return
			}
		}
	}()

	go func() {
		t := time.After(time.Duration(waitSeconds) * time.Second)
		for {
			select {
			case ch2 <- rand.Intn(101):
				time.Sleep(time.Second)
			case <-t:
				fmt.Println("2 time out")
				close(ch2)
				return
			}
		}
	}()

	ch1Closed := false
	ch2Closed := false
    
	for {
		select {
		case d1, ok := <-ch1:
			if !ok {
				ch1Closed = true
			} else {
				fmt.Println("received from ch1:", d1)
			}
		case d2, ok := <-ch2:
			if !ok {
				ch2Closed = true
			} else {
				fmt.Println("received from ch2:", d2)
			}
		}

		if ch1Closed && ch2Closed {
			break
		}
	}
}
最后修改 October 10, 2024: 更新 (a4b8f85)