Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How Golang implements the timeout mechanism

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading