1 回答

TA貢獻1911條經驗 獲得超7個贊
如果使用上下文而不是計時器,則僅在退出函數大小寫條件時調用取消。
package main
import (
"context"
"fmt"
"time"
)
func main() {
ch := make(chan string)
go endProgram(ch)
printFunc(ch)
}
func printFunc(ch chan string) {
for {
ctx, cancel := context.WithTimeout(context.Background(), getTimeoutDuration())
select {
case s := <-ch:
cancel()
fmt.Println(s)
return
case <-ctx.Done():
fmt.Println("Current value")
}
}
}
func endProgram(ch chan string) {
time.Sleep(time.Second * 8)
ch <- "Exit function"
}
func getTimeoutDuration() time.Duration {
return time.Second * 3
}
添加回答
舉報