package main import ( "fmt" "time" ) func deskGoRoutine(index int, userChannel chan string, deskChannel chan string) { for { fmt.Println("deskGoRoutine", index) select { case info := <-userChannel: if info == "userMsg" { fmt.Println(info) deskChannel <- "deskMsg" } case <-time.After(time.Second): fmt.Println("deskGoRoutine", index, "timeout,continue") continue } time.Sleep(time.Second) } } func userGoRoutine(index int, deskChannel chan string, userChannel chan string) { for { fmt.Println("userGoRoutine", index) select { case info := <-deskChannel: if info == "deskMsg" { fmt.Println(info) userChannel <- "userMsg" } case <-time.After(time.Second): fmt.Println("userGoRoutine", index, "timeout,continue") continue } time.Sleep(time.Second) } } func main() { userChannel := make(chan string) deskChannel := make(chan string) go userGoRoutine(0, deskChannel, userChannel) go deskGoRoutine(0, userChannel, deskChannel) userChannel <- "userMsg" select {} }
一个gouRoutine对应一个channel,channel用来同步,如果不加timeout,那么goRoutine在收不到想要的channel数据的时候会死锁,只有加上timeout,才会不断的处理,满足我的需求
本文通过一个Go语言的示例程序展示了如何使用协程和通道进行通信和同步操作。程序中两个协程分别代表用户和服务台,它们通过通道发送消息并设置超时避免死锁。
237

被折叠的 条评论
为什么被折叠?



