How does the Go language handle concurrent timeout in detail

  • 2020-06-03 06:45:07
  • OfStack

Implementation principle:

Concurrent 1 function, waiting for 1s after writing data to timeout, in select If there is data in 1s to others channel If it doesn't, it is timeout If the data is written, we know that it has timed out.

Implementation code:

package main 
import "fmt"
import "time"
func main() {
 ch := make(chan int, 1)
 timeout := make(chan bool, 1)
 //  Concurrent execution 1 A function, wait 1s After the timeout write true
 go func() {
 timeout <- true
 //  There will be a wait ch or timeout Read the data 
 //  because 1 There is no straight ch Write data 
 //  in 1s After the timeout Write data 
 //  So it was executed timeout the case
 //  You can use this technique to implement a timeout 
 select {
 case <- ch :
 fmt.Println("read from ch")
 case <- timeout :
 fmt.Println("time out...")


The above is the whole content of this article, I hope to bring 1 definite help to your study or work, if you have any questions, you can leave a message to communicate.

Related articles: