如何停止goroutine [英] how to stop a goroutine

查看:186
本文介绍了如何停止goroutine的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  ch:= make(chan)

我有一个调用方法的goroutine,并将返回的值传递给频道: int $ 100)
go func(){
for {
ch < - do_stuff()
}
}()
解决方案

编辑: 在意识到你的问题是关于将值发送给goroutine中的chan之前,我急急地写了这个答案。下面的方法可以像上面提到的那样使用一个额外的chan,或者使用这个chan你已经是双向的,你可以使用那个...



如果您的goroutine仅用于处理来自陈的项目,您可以使用关闭内置和特殊的渠道接收表单。



也就是说,一旦你完成了在陈的项目发送,你关闭它。然后在你的goroutine中,你为receive操作符提供了一个额外的参数,它显示频道是否已经关闭。



下面是一个完整的例子(waitgroup用于确保这个过程一直持续到goroutine完成为止):

pre $ $ $ $ $ $ $
$ b $ import $ sync
func main(){
var wg sync.WaitGroup
wg.Add(1)

ch:= make(chan int)
去func {
for {
foo,ok:=< - ch
if!ok {
println(done)
wg.Done()
返回
}
println(foo)
}
}()
ch < - 1
ch < - 2
ch < - 3
close(ch)

wg.Wait()
}


I have a goroutine that calls a method, and passes returned value on a channel:

ch := make(chan int, 100)
go func(){
    for {
        ch <- do_stuff()
    }
}()

How do I stop such a goroutine?

解决方案

EDIT: I wrote this answer up in haste, before realizing that your question is about sending values to a chan inside a goroutine. The approach below can be used either with an additional chan as suggested above, or using the fact that the chan you have already is bi-directional, you can use just the one...

If your goroutine exists solely to process the items coming out of the chan, you can make use of the "close" builtin and the special recieve form for channels.

That is, once you're done sending items on the chan, you close it. Then inside your goroutine you get an extra parameter to the receive operator that shows whether the channel has been closed.

Here is a complete example (the waitgroup is used to make sure that the process continues until the goroutine completes):

package main

import "sync"
func main() {
    var wg sync.WaitGroup
    wg.Add(1)

    ch := make(chan int)
    go func() {
        for {
            foo, ok := <- ch
            if !ok {
                println("done")
                wg.Done()
                return
            }
            println(foo)
        }
    }()
    ch <- 1
    ch <- 2
    ch <- 3
    close(ch)

    wg.Wait()
}

这篇关于如何停止goroutine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆