简体   繁体   English

推迟在go例程中调用

[英]Defer called in go routine

I believe I understand defer well in the normal use cases. 我相信我理解在正常使用情况下会很好。 Such as the one listed in this question Golang defer behavior . 比如这个问题中列出的一种Golang延迟行为 However I am a little perplexed as to what is happening when defer is called inside a goroutine that does not return. 但是,对于在不返回的goroutine中调用defer时发生的情况,我有些困惑。 Here is the code in question. 这是有问题的代码。

func start_consumer() {
    conn, _ := amqp.Dial("amqp://username:password@server.com")
    //defer conn.Close()

    ch, _ := conn.Channel()
    //defer ch.Close()

    q, _ := ch.QueueDeclare(
        "test", // name
        true,   // durable
        false,  // delete when unused
        false,  // exclusive
        false,  // no-wait
        nil,    // arguments
    )

    _ = ch.Qos(
        3,     // prefetch count
        0,     // prefetch size
        false, // global
    )

    forever := make(chan bool)

    go func() {
        for {
            msgs, _ := ch.Consume(
                q.Name, // queue
                "",     // consumer
                false,  // ack
                false,  // exclusive
                false,  // no-local
                false,  // no-wait
                nil,    // args
            )

            for d := range msgs {
                log.Printf("Received a message: %s", d.Body)
                d.Ack(true)
            }

            time.Sleep(1 * time.Second)
        }
    }()

    log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
    <-forever
}

This function is called from 该函数从

go start_consumer()

This is likely a misunderstanding by me how channels work but I though forever would not return since it's waiting for a value to be passed to it. 这对我来说可能是一种误解,但渠道却永远不会返回,因为它正在等待将值传递给它。

The Go Blog's Defer, Panic, and Recover post referenced in the previous question does a great job explaining how defer statements work. 上一个问题中引用的Go Blog的Defer,Panic和Recover帖子在解释defer语句的工作原理方面做得很好。

A defer statement pushes a function call onto a list. defer语句将函数调用推送到列表上。 The list of saved calls is executed after the surrounding function returns. 周围函数返回后,将执行保存的呼叫列表。 Defer is commonly used to simplify functions that perform various clean-up actions. Defer通常用于简化执行各种清理操作的功能。

In your case since the goroutine does not return, the list of deferred calls will never be run. 在您的情况下,由于goroutine不返回,因此延迟调用列表将永远不会运行。 This makes the defer statement unnecessary in this context. 这使得在这种情况下不需要defer语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM