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 时区时差处理方式

个人习惯用 0 时区时间戳记录时间,可以方便转到不同时区,下面介绍 Golang 时区时差处理...

Golang http client 处理重定向网页

假设一个网址有多个重定向,A-B-C-D,使用 http.Client.Get 最后取得的内容是网址D的内容,我们该手动处理包含重定向的网址。...

Golang Web 程序生产环境独立部署示例

一个 web 应用通常是跑在一个前端代理,如 Nginx 后,这样可以方便的在同一个服务器部署多个应用。这里说的独立部署是指让 go web 程序直接暴露在外面,独占 443、80 端口(俗称裸跑)。这样做除了性能有些提高外,更重要的是部署方便。...

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

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms