登录
首页 >  Golang >  Go问答

为什么我的程序中的 goroutine 没有正确关闭?

来源:stackoverflow

时间:2024-02-08 15:00:25 170浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《为什么我的程序中的 goroutine 没有正确关闭?》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~

问题内容

上下文

请仔细阅读代码中的注释。一切都在其中。

如果您有使用 discordgo 的经验

完整的代码可以在这里找到:https://github.com/telephrag/kubinka/tree/bug(参见包 strgmain)添加 goroutine 命令处理程序也会停止正常工作。与数据库交互相关的所有内容(分别在 /deploy 和 /return 上存储和从数据库中删除)根本不起作用。用户仅收到“应用程序未响应”消息,而不是正确的响应(请参阅以 cmd_ 前缀开头的包)。

package main

import (
    "context"
    "fmt"
    "log"
    "os"
    "os/signal"
    "syscall"
    "time"

    "go.etcd.io/bbolt"
)

/*  TO REPRODUCE:
Start the program wait a few seconds and press ^C.
Expect the case of program not shutting down after few attempts.
*/

func WatchExpirations(ctx context.Context, db *bbolt.DB, bkt string) error {
    timeout := time.After(time.Second * 5)
    for {
        select {
        case <-timeout:
            tx, err := db.Begin(true)
            if err != nil {
                return fmt.Errorf("bolt: failed to start transaction")
            }

            bkt := tx.Bucket([]byte(bkt))
            c := bkt.Cursor()
            for k, v := c.First(); k != nil; k, v = c.Next() {
                // do stuff with bucket...
                fmt.Println(v) // check if v matches condition, delete if does

                if err := tx.Commit(); err != nil { // BUG: commiting transaction in a loop
                    tx.Rollback()
                    return fmt.Errorf("bolt: failed to commit transaction: %w", err)
                }
                timeout = time.After(time.Second * 5)
            }

        case <-ctx.Done():
            return ctx.Err()
        }
    }
}

func main() {
    ctx, cancel := context.WithCancel(context.Background())

    db, err := bbolt.Open("kubinka.db", 0666, nil)
    if err != nil {
        log.Panicf("failed to open db %s: %v", "kubinka.db", err)
    }

    if err = db.Update(func(tx *bbolt.Tx) error {
        _, err := tx.CreateBucketIfNotExists([]byte("players"))
        if err != nil {
            return fmt.Errorf("failed to create bucket %s: %w", "players", err)
        }
        return nil
    }); err != nil {
        log.Panic(err)
    }

    defer func() { // BUG?: Panicing inside defer
        if err := db.Close(); err != nil { // will close normally in debug mode
            log.Panicf("error closing db conn: %v", err) // will stuck otherwise
        }
    }()

    // use `ds` to handle commands from user while storing ctx internally

    go func() { // addition of this goroutine prevents program from shutting down
        err = WatchExpirations(ctx, db, "players")
        if err != nil {
            log.Printf("error while watching expirations in db")
            cancel()
        }
    }()

    interrupt := make(chan os.Signal, 1)
    signal.Notify(interrupt, syscall.SIGTERM, syscall.SIGINT)
    for {
        select {
        // as was seen in the debugger this branch is being reached
        // however than program stalls eternally
        case <-interrupt:
            log.Println("Execution stopped by user")
            cancel()
            return // is called but program doesn't stop
        case <-ctx.Done():
            log.Println("ctx cancelled")
            return
        default:
            time.Sleep(time.Millisecond * 200)
        }
    }
}

正确答案


根据 comment in your repo,问题似乎出在这里:

tx, err := db.Begin(true)
if err != nil {
   return fmt.Errorf("bolt: failed to start transaction")
}
bkt := tx.Bucket([]byte(bkt))
c := bkt.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
    // do stuff with bucket...
    fmt.Println(v) // check if v matches condition, delete if does

    if err := tx.Commit(); err != nil { // BUG: commiting transaction in a loop
        tx.Rollback()
        return fmt.Errorf("bolt: failed to commit transaction: %w", err)
    }
    timeout = time.After(time.Second * 5)
}

循环可以迭代 0 次。

  • 如果没有迭代 - tx 未提交且 timeout 未重置(因此 case <-timeout: 将不会再次触发)。
  • 如果有多次迭代 - 您将多次尝试 tx.commit()(出现错误)。

这可能导致了您所看到的问题; bolt Close function

关闭释放所有数据库资源。关闭数据库之前必须关闭所有事务。

因此,如果有一个事务正在运行,clos​​e 会阻塞直到完成(事务开始时内部 bolt 会锁定 mutex,完成时会锁定 releases)。

解决方案是确保事务始终关闭(并且仅关闭一次)。

终于介绍完啦!小伙伴们,这篇关于《为什么我的程序中的 goroutine 没有正确关闭?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

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