Last active
July 30, 2018 19:12
-
-
Save dlipovetsky/2e594e04404a5881b197d1131b262c4a to your computer and use it in GitHub Desktop.
Example of goroutine leak when using time.After with an unbuffered channel
This file contains 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 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