How to kill goroutines? [duplicate]

半世苍凉 提交于 2019-12-07 14:10:09

问题


I would like to know how to kill/stop goroutines. All examples are based on channels and select, which seems to only work if the goroutine contains some repeating task between which it can listen on a channel. Is there a way to stop the below goroutine before it returns?

package main

import (
        "time"
)

func main() {
    stop := make(chan string, 1)

    go func() {
        time.Sleep(10 * time.Second)
        stop <- "stop"
        return
    }()
    <- stop
}

回答1:


Is there a way to stop the below goroutine before it returns?

No there is not (except calling os.Exit to abort the whole program).

Goroutines are self-contained and not controllable from the outside.



来源:https://stackoverflow.com/questions/51941132/how-to-kill-goroutines

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!