如何使用一个通道来取消goroutines(附实例)

53 阅读1分钟

取消goroutines有很多选择,但这个例子告诉我们如何使用一个通道来达到这个目的。我们将运行三个goroutine,只要其中一个写到 "done "通道,其他的就会被终止。每个goroutine都要打印三次。

例子

package main

import (
	"log"
	"time"
)

func main() {
	done := make(chan struct{})

	go run(done, 1)
	go run(done, 2)
	time.Sleep(time.Second) // Cause the last one to not complete all three jobs
	go run(done, 3)

	<-done
}

func run(done chan<- struct{}, id int) {
	i := 1

	ticker := time.NewTicker(time.Second)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			// Do something here
			log.Println(id, "- done", i)

			i++
			if i == 4 {
				done<- struct{}{}
			}
		}
	}
}

结果

如下图所示,第三个goroutine没有变化,运行了三次:

2020/06/16 22:32:24 2 - done 1
2020/06/16 22:32:24 1 - done 1
2020/06/16 22:32:25 2 - done 2
2020/06/16 22:32:25 1 - done 2
2020/06/16 22:32:25 3 - done 1
2020/06/16 22:32:26 1 - done 3
2020/06/16 22:32:26 2 - done 3