dsfdsfdsfdsf1223 2015-01-14 16:05
浏览 64
已采纳

终止第二个goroutine

I have the following code snippet.

package main

import (
    "errors"
    "fmt"
    "time"
)

func errName(ch chan error) {

    for i := 0; i < 10000; i++ {

    }

    ch <- errors.New("Error name")
    close(ch)
}

func errEmail(ch chan error) {

    for i := 0; i < 100; i++ {

    }
    ch <- errors.New("Error email")
    close(ch)
}

func main() {

    ch := make(chan error)

    go errName(ch)
    go errEmail(ch)
    fmt.Println(<-ch)
    //close(ch)

    time.Sleep(1000000)

}

As you can see, I let two functions run in the goroutine, errName and errEmail. I pass as parameter a channel with error type. If one of them finish first, it should send the error through the channel and close it. So the second, still running goroutine, have not to run anymore, because I've got the error already and I want to terminate the still running goroutine. This is what I trying to reach in my example above.

When I run the programm, I've got error

panic: send on closed channel

goroutine 6 [running]:
main.errEmail(0xc0820101e0)
        D:/gocode/src/samples/gorountine2.go:24 +0xfd
created by main.main
        D:/gocode/src/samples/gorountine2.go:33 +0x74

goroutine 1 [runnable]:
main.main()
        D:/gocode/src/samples/gorountine2.go:34 +0xac
exit status 2

I know, when I remove the close statement, it would not panic, but channel on the running goroutine is still waiting for error reference and that's mean, it wasted the memory for nothing(waiting).

When one of them send an error to the channel, the second error I will do not care anymore, that is my target.

  • 写回答

3条回答 默认 最新

  • dpdp42233 2015-01-14 19:47
    关注

    A standard way to organize this behaviors is to use

    package main
    
    import (
        "fmt"
        "time"
    
        "code.google.com/p/go.net/context"
    )
    
    func errName(ctx context.Context, cancel context.CancelFunc) {
        for i := 0; i < 10000; i++ {
            select {
            case <-ctx.Done():
                return
            default:
            }
        }
        cancel()
    }
    
    func errEmail(ctx context.Context, cancel context.CancelFunc) {
    
        for i := 0; i < 100; i++ {
            select {
            case <-ctx.Done():
                return
            default:
            }
        }
        cancel()
    }
    
    func main() {
    
        ctx := context.Background()
    
        ctx, cancel := context.WithCancel(ctx)
    
        go errName(ctx, cancel)
        go errEmail(ctx, cancel)
    
        <-ctx.Done()
    
        if ctx.Err() != nil {
            fmt.Println(ctx.Err())
        }
    
        time.Sleep(1000000)
    
    }
    

    You can read two good articles on the matter:

    1. http://blog.golang.org/context
    2. http://blog.golang.org/pipelines
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)