Created
October 7, 2018 00:32
-
-
Save kelby/0bb1023067e7fb19c401b79c3630787e to your computer and use it in GitHub Desktop.
Golang 让 for 循环运行一段时间超时自动退出
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func main() { | |
timeout := time.After(time.Second * 10) | |
finish := make(chan bool) | |
count := 1 | |
go func() { | |
for { | |
select { | |
case <-timeout: | |
fmt.Println("timeout") | |
finish <- true | |
return | |
default: | |
fmt.Printf("haha %d\n", count) | |
count++ | |
} | |
time.Sleep(time.Second * 1) | |
} | |
}() | |
<-finish | |
fmt.Println("Finish") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment