什么是Goroutine?怎么退出Goroutine?
goroutine类似线程,但是goroutine是由Go运行时runtime调度和管理的,Go程序会智能地将goroutine中的任务合理分配给每个CPU,因为它在内置了调度和上下文切换的机制。
Goroutine退出方式:
- 关闭通道
- 定期轮询
- 使用context
关闭通道使用close机制
ch := make(chan string, 5)
go func() {
for {
v, ok := <-ch
if !ok {
return
}
fmt.Println(v)
}
}()
ch <- "你好"
ch <- "世界"
close(ch)
time.Sleep(2 * time.Second)
定期轮询
ch := make(chan string, 5)
done := make(chan struct{})
go func() {
for {
//ch <- "你好,世界!" 阻塞操作
select {
case ch <- "你好,世界!": // 非阻塞操作
case <-done:
close(ch)
return
}
}
}()
go func() {
time.Sleep(3 * time.Second)
done <- struct{}{}
}()
for i := range ch {
fmt.Println(i)
}
使用context
ch := make(chan struct{})
ctx, cancel := context.WithCancel(context.Background())
go func(ctx context.Context) {
for {
select {
case <-ctx.Done():
ch <- struct{}{}
return
default:
fmt.Println("hello")
}
}
}(ctx)
go func() {
time.Sleep(time.Second * 2)
cancel()
}()
<-ch // 阻塞
思考:可以在Goroutine A中关闭Goroutine B吗?
在 Go 语言中,goroutine 是无法直接关闭另一个 goroutine 的。Go 提供了一种通过通信来管理并发的方式,即通过使用 channels 和 context 来协调多个 goroutine 的工作,控制其生命周期。