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

报告相同问题?