Last active
October 8, 2015 12:18
-
-
Save localhots/234cab85a1c0a48601c7 to your computer and use it in GitHub Desktop.
Writing to a closed channel in Go lang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func main() { | |
chans := []chan int{ | |
make(chan int, 1), | |
make(chan int, 1), | |
make(chan int, 1), | |
make(chan int, 1), | |
make(chan int, 1), | |
} | |
close(chans[1]) // closing random channel | |
close(chans[4]) // closing one more random channel | |
closed := []int{} | |
for i, ch := range chans { | |
go func(i int, ch chan int) { | |
defer func() { | |
// recoverint from panic caused by writing to a closed channel | |
if recover() == nil { | |
return | |
} | |
fmt.Println("Channel", i, "is closed. Removing it from the list") | |
closed = append(closed, i) | |
}() | |
ch <- 1 // writing to channel which may be already closed | |
}(i, ch) | |
} | |
time.Sleep(1) | |
deleted := 0 | |
for _, i := range closed { | |
chans = append(chans[:i-deleted], chans[i-deleted+1:]...) | |
deleted++ | |
} | |
fmt.Println(len(chans), "channels left") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment