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 库推荐

Google 的翻译越来越好了,官方的Golang SDK 已经很完美,这里介绍的是几个非官方发布的有特色的库。...

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

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

Golang quicktemplate 模版快速入门

Golang 有很多的模版引擎,自带的 `html/template` 也很好,大多数情况都能满足需求,只是有些逻辑、条件判断不好在模版里实现, `quicktemplate` 是个很好的选择。...

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

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