教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 Go如何杀死goroutine?

Go如何杀死goroutine?

发布时间:2022-03-19   编辑:jiaochengji.com
教程集为您提供Go如何杀死goroutine?等资源,欢迎您收藏本站,我们将为您提供最新的Go如何杀死goroutine?资源
<textarea id="append-test" style="display:none;">在函数里开一个 goroutine 并不会因为函数的结束而退出,所以以下有一段代码是我在网站上找到的,我略作修改,以证明这种办法无法让goroutine退出,在函数终结退出后,依然有routine在奔跑, 请教大家如何杀死goroutine?不甚感激:::: for { go 拜谢() } http://bbs.mygolang.com/thread-18-1-1.html package main import ( "fmt" "runtime" "time" ) func job(ch int, timeout time.Duration) { t := time.NewTimer(timeout) defer t.Stop() flg := make(chan bool, 1) //执行真正的处理,这里用sleep模拟 go func(tm int) { i := 0 for i &lt; tm { fmt.Println(ch, "is running...") i time.Sleep(1 * time.Second) } flg &lt;- true }(ch) //监听通道,由于设有超时,不可能泄露 select { case &lt;-t.C: fmt.Println(ch, "time out") case &lt;-flg: //正常退出 fmt.Println("job", ch, "end") return } } func main() { runtime.GOMAXPROCS(4) timeout := 10 * time.Second //启动3个goroutine,若超时的话会自动退出 go job(1, timeout) go job(200, timeout) go job(5, timeout) time.Sleep(60 * time.Second) } </textarea>
到此这篇关于“Go如何杀死goroutine?”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
Go如何杀死goroutine?
Goroutine的调度分析(一)
简单理解 Goroutine 是如何工作的
golang 切片截取 内存泄露_怎么看待Goroutine 泄露
Go:Goroutine 的切换过程实际上涉及了什么
goroutine泄露:原理、场景、检测和防范
2018年最全Go语言教程零基础入门到进阶实战视频
Goroutine并发调度模型深度解析&amp;手撸一个协程池
Go并发模式:管道和取消
goroutine 调度器

[关闭]
~ ~