TheRiver | blog

You have reached the world's edge, none but devils play past here

0%

when goroutine quit

demo

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
func main() {
defer func() {
fmt.Println("main defer")
}()

go func() {
defer fmt.Println("one defer")
go func() {
defer fmt.Println("two defer")
f2, err := os.OpenFile("log2", os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
panic("open err")
}
write := bufio.NewWriter(f2)
defer f2.Close()
for {
write.WriteString("two here\n")
write.Flush()

time.Sleep(2 * time.Second)
}
}()

f1, err := os.OpenFile("log1", os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
panic("open err")
}
write := bufio.NewWriter(f1)
defer f1.Close()

for i := 1; i < 3; i++ {
write.WriteString("one here\n")
write.Flush()

time.Sleep(1 * time.Second)
}
}()

time.Sleep(10 * time.Second)
fmt.Println("main exit")
}

output

1
2
3
one defer
main exit
main defer

log1

1
2
one here
one here

log2

1
2
3
4
5
two here
two here
two here
two here
two here

conclusions

  • main routine quit, all other routine quit
  • a routine(not main) quit, child routine unaffected
  • use channel/context to exit other routine
----------- ending -----------