duanliang1019 2018-09-18 10:50
浏览 43
已采纳

通过Go通道流数据

I'm trying to build a function that I pass a channel to and when run in a go routine it will constantly post updates (in this instance, values of sin) to a channel. When data is sent the the channel, I then want to send it over a web socket.

func sineWave(value chan float64) {
    var div float64
    sinMult := 6.2839
    i := 0
    log.Println("started")

    for {
        div = (float64(i+1) / sinMult)
        log.Println(math.Sin(div))
        time.Sleep(100 * time.Millisecond)
        value <- math.Sin(div)
        // log.Println()

        i++
        if i == 45 {
            i = 0
        }
    }
    // log.Println(math.Sin(div * math.Pi))
}

It seems to get stuck at value <- main.Sin(div) stopping the rest of main() from running. How do i get sineWave to run indefinitely in the background and to print its output in another function as they arrive?

  • 写回答

1条回答 默认 最新

  • dongpan8439 2018-09-18 11:17
    关注

    There is several mistakes in this code,

    • the value chan is never drained, so any write will block
    • the value chan is never closed, so any drain will be infinite

    A channel must always be drained, a channel must be closed at some point.

    Also, please post reproducible examples, otherwise it is difficult to diagnose the issue.

    This is a slightly modified but working version of the OP code.

    package main
    
    import (
        "fmt"
        "math"
        "time"
    )
    
    func sineWave(value chan float64) {
        defer close(value) // A channel must always be closed by the writer.
        var div float64
        sinMult := 6.2839
        i := 0
        fmt.Println("started")
    
        for {
            div = (float64(i+1) / sinMult)
    
            time.Sleep(100 * time.Millisecond)
            value <- math.Sin(div)
    
            i++
            if i == 4 {
                // i = 0 // commented in order to quit the loop, thus close the channel, thus end the main for loop
                break
            }
        }
    
    }
    
    func main() {
        value := make(chan float64)
        go sineWave(value) // start writing the values in a different routine
        // drain the channel, it will end the loop whe nthe channel is closed
        for v := range value {
            fmt.Println(v)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#网络安全#的问题:求ensp的网络安全,不要步骤要完成版文件
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥20 使用Photon PUN2解决游戏得分同步的问题
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序