Skip to content

Instantly share code, notes, and snippets.

@dlipovetsky
Last active July 30, 2018 19:12
Show Gist options
  • Save dlipovetsky/2e594e04404a5881b197d1131b262c4a to your computer and use it in GitHub Desktop.
Save dlipovetsky/2e594e04404a5881b197d1131b262c4a to your computer and use it in GitHub Desktop.
Example of goroutine leak when using time.After with an unbuffered channel
package timeafterleak_test
import (
"log"
"testing"
"time"
"github.com/fortytw2/leaktest"
)
func TestUnbuffered(t *testing.T) {
defer leaktest.Check(t)()
ch := make(chan string)
waitForResult(ch)
}
func TestBuffered(t *testing.T) {
defer leaktest.Check(t)()
ch := make(chan string, 1)
waitForResult(ch)
}
func waitForResult(ch chan(string)) {
go func() {
time.Sleep(500 * time.Millisecond)
ret := "done"
ch <- ret
}()
select {
case res := <-ch:
log.Println(res)
case <-time.After(100 * time.Millisecond):
log.Println("timed out")
}
}
~
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment