Skip to content

Instantly share code, notes, and snippets.

@chaleaoch
Last active April 19, 2023 06:13
Show Gist options
  • Save chaleaoch/c0afd17de3927f6712858e1b422685b2 to your computer and use it in GitHub Desktop.
Save chaleaoch/c0afd17de3927f6712858e1b422685b2 to your computer and use it in GitHub Desktop.
for select 用法, 当channel被关闭, 利用ok判断并重置为nil. select 将忽略
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