我是靠谱客的博主 痴情水蜜桃,这篇文章主要介绍Go 如何优雅的关闭goroutine,现在分享给大家,希望可以做个参考。

1. Context包方式

复制代码
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
34
35
36
37
38
package main import ( "context" "fmt" "sync" "time" ) var wg =new(sync.WaitGroup) //创建一个等待组 func main(){ ctx,cancel := context.WithCancel(context.Background()) wg.Add(1) //等待组计数+1 go work1(ctx) //跑一个work1 goroutine exit_with_second(5,cancel) //设置sleep 5秒执行cancel() wg.Wait() //等待组计数为0 释放阻塞 } func work1(ctx context.Context){ LOOP: for{ time.Sleep(time.Second*1) select { case x := <-ctx.Done(): fmt.Println("work1 rev :",x) break LOOP default: fmt.Println("work1...") } } fmt.Println("work1 done ...") wg.Done() //等待组计数-1 } func exit_with_second(s int,f context.CancelFunc){ time.Sleep(time.Second * time.Duration(s)) f() //执行 }

2. Channel方式

复制代码
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
34
35
36
37
38
39
40
41
package main import ( "fmt" "sync" "time" ) var wg = new(sync.WaitGroup) func main(){ var ch = make(chan int) //创建一个管道 defer close(ch) //程序退出前关闭管道 wg.Add(1) go work1(ch) //执行一个work1 goroutine sendnumber(5,ch) wg.Wait() } func work1(c chan int){ LOOP: for { time.Sleep(time.Second * 1) select { case n := <-c : fmt.Println("work1 rev:",n) break LOOP // 从管道接收到数字1 退出循环 default: fmt.Println("work1 ...") } } fmt.Println("work1 done") wg.Done() } func sendnumber(n int,c chan int){ time.Sleep(time.Second * time.Duration(n)) c <- 1 // 往管道发送数字1 }

最后

以上就是痴情水蜜桃最近收集整理的关于Go 如何优雅的关闭goroutine的全部内容,更多相关Go内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(61)

评论列表共有 0 条评论

立即
投稿
返回
顶部