回答

收藏

如何停止一个goroutine

技术问答 技术问答 314 人阅读 | 0 人回复 | 2023-09-11

我有一个调用方法 goroutine,并在通道上传递返回值:
) S: U0 x, R) D% l

      J0 v6 b& p3 F3 K  B# b. F7 W, @
  • ch := make(chan int,100)go func(){    for              ch 如何停止这样的 ?goroutine?2 E4 R, d& R  Q/ @( M. M
  •                                                                6 Z/ j! p; O3 _! O
  •     解决方案:                                                               
    $ C9 Q; x$ A# B' w
  •                                                                 通常,你去 goroutine 传输一个信号通道(可能是单独的)。当你想要 goroutine 停止时,信号通道用于推入值。goroutine 定期轮询通道。一旦检测到信号,它会退出。[code]quit := make(chan bool)go func()      for              select              case <- quit:            return        default:       Do other stuff     Do stuff// Quit goroutinequit <- true7 }- S+ |7 h0 X  ]$ z0 N
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则