Golang无限循环超时

Golang无限循环超时,go,concurrency,Go,Concurrency,我正在尝试读取一个恒定的数据流,如果调用接收流的时间超过30秒,我需要超时并退出程序。我不知道在收到超时后如何退出go例程 func ReceiveStreamMessages(strm Stream, msg chan<- []byte) error { d := make(chan []byte, 1) e := make(chan error) tm := time.After(30 * time.Second) go func() { for {

我正在尝试读取一个恒定的数据流,如果调用接收流的时间超过30秒,我需要超时并退出程序。我不知道在收到超时后如何退出go例程

func ReceiveStreamMessages(strm Stream, msg chan<- []byte) error {
  d := make(chan []byte, 1)

  e := make(chan error)

  tm := time.After(30 * time.Second)

  go func() {
    for {
        //blocking call
        data, err := strm.Recv()
        if err != nil {
            e <- err
            return
        }
        select {
        case d <- data.Result:
        case <-tm:
            //exit out go routine
            return
         }
      }
  }()

  for {
    select {
    case message := <-d:
        msg <- message
    case err := <-e:
        return err
    case <-tm:
        return nil
    }
  }
}

func ReceiveStreamMessages(strm Stream,msg chan使用
context
package
WithTimeout
。类似如下:

package main

import (
    "context"
    "fmt"
    "sync"
    "time"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
    // prepare
    ...
    // wait group just for test
    var wg sync.WaitGroup
    wg.Add(1)
    go func() {
        for {
            select {
            case d <- data.Result:
               // do something
            case <-ctx.Done():
                fmt.Println("Done")
                wg.Done()
                return
            }
        }
    }()
    wg.Wait()
    cancel()
    fmt.Println("Hello, playground")
}
主程序包
进口(
“上下文”
“fmt”
“同步”
“时间”
)
func main(){
ctx,cancel:=context.WithTimeout(context.Background(),1*time.Second)
//预备
...
//等待测试
var wg sync.WaitGroup
工作组.添加(1)
go func(){
为了{
挑选{

案例d“退出父函数是否足以退出go例程”不。Go例程一直运行,直到主线程处于活动状态;似乎您只需要使用带有timeoutHmmm的上下文,我不确定如何使用上下文来解决我的问题?如果我在Go例程选择中用上下文信号替换超时,我不就是现在的位置吗?两个通道都准备好接收了吗?也许我错过了一些你能提供一个例子吗?请读这个