zoukankan      html  css  js  c++  java
  • 贴一段demo代码,演示channel之间的同步

    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,才会不断的处理,满足我的需求

  • 相关阅读:
    【转】【矩阵】坐标的矩阵变换
    cocos2d-x聊天气泡
    lua自用的函数收集
    lua错误收集
    cocos2d-x中CCEditbox导出到lua
    love2d杂记9--光照效果
    (转)love2d有用的辅助库--gamework
    XPath语法 在C#中使用XPath示例
    WCF的CommunicationObjectFaultedException异常问题
    WCF绑定(Binding)
  • 原文地址:https://www.cnblogs.com/ziyouchutuwenwu/p/3837424.html
Copyright © 2011-2022 走看看