-
Notifications
You must be signed in to change notification settings - Fork 0
/
sender_after_error_check.go
58 lines (45 loc) · 1.36 KB
/
sender_after_error_check.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package leak
import (
"errors"
"github.com/devlights/gomy/output"
)
// SenderAfterErrorCheck -- goroutineリークが発生するパターンのサンプルです。
//
// チャネルの送受信の実装があるが、内部の処理結果によっては送信側がいなくなってしまうパターン。
// 受信側のgoroutineが永遠に待ち続けるので終了しません。
//
// 解決方法としては、送信側が適切に使い終わったチャネルを閉じること。
//
// REFERENCES:
// - https://betterprogramming.pub/common-goroutine-leaks-that-you-should-avoid-fe12d12d6ee
func SenderAfterErrorCheck() error {
var (
ch = make(chan int)
proc = func() bool {
return false
}
fn = func(ch <-chan int) {
data := <-ch
output.Stdoutl("[recv]", data)
}
)
go fn(ch)
if !proc() {
return errors.New("this is dummy error")
}
//
// 上でエラーが発生した場合、以下は処理されない。
// なので、上で起動しているgoroutineは永遠に受信待機することになる。
//
ch <- 1
return nil
/*
$ task
task: [build] go build .
task: [run] ./try-golang -onetime
ENTER EXAMPLE NAME: goroutines_leak_sender_after_error_check
[Name] "goroutines_leak_sender_after_error_check"
[Elapsed] 20.16µs
[Error] this is dummy error (goroutines_leak_sender_after_error_check)
*/
}