Last active
April 19, 2023 06:13
-
-
Save chaleaoch/c0afd17de3927f6712858e1b422685b2 to your computer and use it in GitHub Desktop.
for select 用法, 当channel被关闭, 利用ok判断并重置为nil. select 将忽略
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| go func() { | |
| // in for-select using ok to exit goroutine | |
| for { | |
| select { | |
| case x, ok := <-in1: | |
| if !ok { | |
| in1 = nil | |
| } | |
| // Process | |
| case y, ok := <-in2: | |
| if !ok { | |
| in2 = nil | |
| } | |
| // Process | |
| case <-t.C: | |
| fmt.Printf("Working, processedCnt = %d\n", processedCnt) | |
| } | |
| // If both in channel are closed, goroutine exit | |
| if in1 == nil && in2 == nil { | |
| return | |
| } | |
| } | |
| }() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment