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.
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:
Use another channel to signal done:
package main
import (
"errors"
"fmt"
"time"
)
func errName(ch chan error, done chan struct{}) {
for i := 0; i < 10000; i++ {
select {
case <-done:
fmt.Println("early return from name")
return
default:
}
}
select {
case: ch <- errors.New("Error name")
default:
}
}
func errEmail(ch chan error, done chan struct{}) {
for i := 0; i < 100; i++ {
select {
case <-done:
fmt.Println("early return from email")
return
default:
}
}
select {
case ch <- errors.New("Error email"):
default:
}
}
func main() {
ch := make(chan error, 1)
done := make(chan struct{})
go errName(ch, done)
go errEmail(ch, done)
fmt.Println(<-ch)
close(done)
time.Sleep(1000000)
}
To prevent the losing goroutine from blocking forever on channel send, I created the error channel with capacity 1 and use a select when sending:
select {
case ch <- errors.New("Error email"):
default:
}
If you are working with more than one level of goroutine completion, then you should consider using golang/x/net/context Context.
Done chan struct{}
mentioned (or its context.Context
incarnation) is the idiomatic and THE TRUE way for behaviour. But the easy way to avoid panic in your snippet can be
import "sync"
var once sync.Once
func errName(ch chan error) {
for i := 0; i < 10000; i++ {
}
once.Do(func() {ch <- errors.New("Error name"); close(ch)}())
}
func errName(ch chan error) {
for i := 0; i < 10000; i++ {
}
once.Do(func() {ch <- errors.New("Error name"); close(ch)}())
}