doutan1875 2018-11-06 06:39
浏览 64
已采纳

为什么在我使函数超时时不调用延迟?

When I add a defer in a function I expect that it will be always called when the function ends. I noticed that it does not happen when the function is times out.

package main

import (
    "context"
    "fmt"
    "time"
)

func service1(ctx context.Context, r *Registry) {
    ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
    defer func() {
        r.Unset("service 1")
    }()
    r.Set("service 1")
    go service2(ctx, r)

    select {
    case <-ctx.Done():
        cancel()
        break
    }
 }

 func service2(ctx context.Context, r *Registry) {
    defer func() {
        r.Unset("service 2")
    }()

    r.Set("service 2")

    time.Sleep(time.Millisecond * 300)
 }

         type Registry struct {
    entries map[string]bool
 }

 func (r *Registry)Set(key string) {
    r.entries[key] = true
 }

 func (r *Registry)Unset(key string)  {
    r.entries[key] = false
 }

 func (r *Registry)Print() {
    for key, val := range r.entries  {
        fmt.Printf("%s -> %v
", key, val)
    }
 }

 func NewRegistry() *Registry {
    r := Registry{}
    r.entries = make(map[string]bool)

    return &r
 }

func main() {
    r := NewRegistry()

    ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*200)

    go service1(ctx, r)
    // go service3(ctx, r)

    select {
    case <-ctx.Done():
        fmt.Printf("context err: %s
", ctx.Err())
        cancel()
    }

    r.Print()
 }

In the example above, the defer in service2() is never called and that's why the output is:

service 1 -> false
service 2 -> true

instead of

service 1 -> false
service 2 -> false

I understand that timeout means "stop executing" but it's reasonable to me execute deferred code. I could not find any explanation of this behavior.

And the second part of the question - how to modify the service or Registry to be resistant to such situations?

  • 写回答

1条回答 默认 最新

  • dpbv85276 2018-11-06 09:37
    关注

    Answer of 1st part

    Say you have a function f1() which uses defer to call f2(), i.e. defer f2() . The fact is that the f2 will be called if and only if f1 completes even if a run-time panic occurs. More specifically, look at go-defer.

    Now our concern is about using defer in goroutine. We also have to remember that a go-routine exits if it's parent function completes of exits.

    So if we use defer in a go-routine function, then if the parent fuction completes or exits, then go-routine function must exit. Since it exits (not completes) the defer statement will not execute. It will be clear we draw the state of your program. enter image description here As you see,

    • at 1st millisecond, service1() completes before others. So, service2() exits without executing defer statement and 'service 2' won't be set to false. Since service1() completes, it's defer will execute and 'service 1' will be set to false.
    • at 2nd millisecond, the main() completes and program finishes.

    So we see how this program executes.

    Answer of 2nd part

    One possible solution i tried is increase time in service1() or decrease time in service2().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制