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 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。