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

  • 相关阅读:
    动手动脑
    加减乘除
    测试
    Java学习的第五十六天
    Java学习的第五十五天
    js判断一个时间是否在某一个时间段内
    js计算两个时间相差多少分钟
    js分钟转化为小时并且以某个数字进行递增
    关于Js debounce(防抖)函数和throttle(节流)小结
    webpack配置scss
  • 原文地址:https://www.cnblogs.com/ziyouchutuwenwu/p/3837424.html
Copyright © 2020-2023  润新知