GolangNote

Golang笔记

Golang 给运行中的goroutine 发送终止信号

Permalink

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

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

Go: 给运行中的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")
}

输出:

plaintext: 给运行中的goroutine 发送终止信号输出
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 转摘请注明来源

Related articles

Golang sync.WaitGroup 的 Wait 超时处理

sync.WaitGroup 使用 `Add(1)`、`Done()`、`Wait()`组合来实现多协程等待,如果某一协程未能合理处理错误,导致无法退出,此时需要引入超时机制。下面是一种超时处理方法。...

Write a Comment to "Golang 给运行中的goroutine 发送终止信号"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 1ms