When using goroutine, I want to avoid blocking caused by program timeout. (e.g. file reading)
Can you give me some sample code. Thanks a lot!
>Solution :
If I understand you correctly, here are the code you want:
go func() {
for {
select {
case num := <-ch: //If there is data, it is printed below. But there is a possibility that "ch" has been no data
fmt.Println("num = ", num)
case <-time.After(3 * time.Second): //The above ch if there has been no data will block, then select will also detect other case conditions, detected 3 seconds after the timeout
fmt.Println("timeout")
quit <- true
}
}
}() //Don't forget()
I hope I can help you! Let me know if this work.