首页 > 代码库 > 贴一段demo代码,演示channel之间的同步
贴一段demo代码,演示channel之间的同步
package mainimport ( "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,才会不断的处理,满足我的需求
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。