goroutine 运行机制是不能外部终止,只能通过 channel 来与它通信,通过 channel 给goroutine 发送终止信号

下面用一个简单的例子说明上面的问题

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
package main

import (
    "fmt"
    "time"
)

func main() {
    quit := make(chan struct{})
    go func() {
        for {
            select {
            case <-quit:
                fmt.Println("here 3")
                return
            default:
                // Do other stuff
                fmt.Println("here 4")
                time.Sleep(10 * time.Second)
                fmt.Println("here 5")
            }
        }
    }()

    // Do stuff
    fmt.Println("here 1")

    time.Sleep(2 * time.Second)
    fmt.Println("here 6")
    // Quit goroutine
    quit <- struct{}{}
    fmt.Println("here 2")
}

输出:

1
2
3
4
5
6
here 1
here 4
here 6
here 5
here 3
here 2
goroutine

本文网址: https://golangnote.com/topic/219.html 转摘请注明来源