通过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?

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)
    }
}