Last active
May 21, 2020 17:48
-
-
Save YabZhang/fb12c16262a83c5df87e7f0556d0097f to your computer and use it in GitHub Desktop.
chan_timeout
This file contains hidden or 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() { | |
| fmt.Println("start...", time.Now()) | |
| timeout := make(chan bool, 1) // 超时信号传输通道 | |
| go func() { // 新起协程传输控制信号; Sleep 1s后延迟释放 | |
| time.Sleep(1 * time.Second) | |
| timeout <- true | |
| }() | |
| ch := make(chan string) // 这里是一个数据通道(不知道何时会返回数据;这里永不反回) | |
| select { | |
| case msg := <-ch: // 这里尝试从数据通道获取数据(实际上永不反回) | |
| fmt.Println("get from ch: ", msg) | |
| case <-timeout: // 1s后timeout通道触发超时信号 | |
| fmt.Println("timeout!") | |
| } | |
| fmt.Println("end...", time.Now()) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment