登录
首页 >  Golang >  Go问答

通知 goroutine 在通道关闭时停止

来源:stackoverflow

时间:2024-04-26 22:00:34 391浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《通知 goroutine 在通道关闭时停止》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我有多个 goroutine,select 来自两个通道:一个 chan 提供数据,一个 chan 用于信号(一种完成/退出通道)。

我使用信号通道来捕获信号(kill)并优雅地关闭 goroutine。

我正在运行 package a 中的“worker”goroutine,而捕获信号的 goroutine 函数则从 package b 运行。

我使用 https://gist.github.com/reiki4040/be3705f307d3cd136e85 中的信号包。

package a

import "sync"

workchan := make(chan int)
quitchan := make(chan struct{})

func stop() {
        fmt.println("stop called, closing channel")
        close(quitchan)
}

func work(wg *sync.waitgroup) {
    var item int
    for {
        select {
        case item = <- workchan:
            ... processing
        case <- quitchan:
            wg.done()
            return
        }
    }
}

捕获信号的goroutine,并调用a.stop()

package b

import (
    "os/signal"
    "os"
    "syscal"
    "a"
)

func signal() {

    schan := make(chan os.signal, 1)
    signal.notify(signalchan, syscall.sigterm, syscall.sigint)

    for {
        s := <-schan
        switch s {
        case os.interrupt, syscall.sigterm:
            a.stop()
        }
    }
}

这是我的主要功能

package main

import (
    "a"
    "b"
    "sync"
)

func main() {

    var wg sync.WaitGroup

    go b.Signal()

    wg.Add(1) // for simplicity; actual code start multiple goroutines of Work
    go a.Work(&wg)

    // wait until work is done
    wg.Wait()
    fmt.Println("Done.")
}

当我终止正在运行的进程时,我看到来自 quit 的打印消息。我预计,一旦通道关闭,goroutines 将在某个时刻 select quitchan 情况并返回。

但他们继续奔跑;他们继续处理来自 workchan 的项目。似乎它被忽略了。我在这里缺少什么? 通道不会被关闭吗?怎么还开着?


解决方案


首先我认为你应该做一个简单的测试,然后把它过去。让其他人了解您的问题会更有帮助。

我改变了你的代码,让它像 go 代码一样阅读,而不是其他语言。 现在成功了

在你的代码中,有一些错误,我将其标记为error注释。有些是语法错误,例如创建 workchan。有些是类型错误。

你应该知道的一件导入设计事情,当你想在执行 stop() 后退出时,你应该关闭向 workchan 发送数据的 workchan,而不是在收到日期时返回。

  • a.go

    package a
    
    import (
        "fmt"
        "sync"
    )
    
    // error: can not do make in global
    var workchan chan int
    var quitchan chan struct{}
    
    // create chan when init
    func init() {
        fmt.println("init a")
        workchan = make(chan int)
        quitchan = make(chan struct{})
    }
    
    func stop() {
        fmt.println("stop called, closing quit channel")
        close(quitchan)
    }
    
    // close the work channel where you send date
    func start(wg *sync.waitgroup) {
        i := 0
        for {
            select {
            case <-quitchan:
                fmt.println("closing work chan")
                close(workchan)
                wg.done()
                return
            default:
                workchan <- i
                i++
            }
        }
    }
    
    // work will exit when workchan closed
    func work(wg *sync.waitgroup) {
        for item := range workchan {
            fmt.printf("receive %d\n", item)
        }
        wg.done()
        fmt.println("work exit")
    }
  • b.go

    package b
    
    import (
        "github.com/shitaibin/awesome/a"
        "os"
        "os/signal"
        "syscall"
    )
    
    func signal() {
    
        schan := make(chan os.signal, 1)
        signal.notify(schan, syscall.sigterm, syscall.sigint) // error
    
        for {
            s := <-schan
            switch s {
            case os.interrupt, syscall.sigterm:
                a.stop()
                return // should return free resource
            }
        }
    }
  • main.go

    package main
    
    import (
        "fmt"
        "github.com/shitaibin/awesome/a"
        "github.com/shitaibin/awesome/b"
        "sync"
    )
    
    func main() {
    
        var wg sync.waitgroup
    
        go b.signal()
    
        wg.add(1)      // for simplicity; actual code start multiple goroutines of work
        go a.work(&wg) // error: pointer
    
        wg.add(1)
        go a.start(&wg) // send data and close channel when stop
    
        // wait until work is done
        wg.wait()
        fmt.println("done.")
    }
  • 结果

    // omit
    Receive 87028
    Receive 87029
    Receive 87030
    Receive 87031
    Receive 87032
    Receiv^C101    <---- send signal here
    Receive 87102
    Receive 87103
    Receive 87104
    Receive 87105
    Receive 87106
    Receive 87107
    Receive 87108
    Receive 87109
    Receive 87110
    Stop called, closing quit channel
    Receive 87111
    Receive 87112
    Closing work chan
    Work exit
    Done.

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>