登录
首页 >  Golang >  Go问答

如何在调试时停止时间而不进行单步执行?

来源:stackoverflow

时间:2024-02-13 10:48:24 452浏览 收藏

golang学习网今天将给大家带来《如何在调试时停止时间而不进行单步执行?》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

当调试使用 context.withtimeout 的程序时,当您没有单步执行各行时,时钟会持续滴答作响,因此在您可以调试依赖于给定上下文的代码段之前,该上下文已完成,因此您所在的代码段有兴趣调试不执行。例如,在下面的代码片段中,我必须增加 timestamp 值才能单步执行 do()retry() ,否则在我执行此操作之前就会超时:

package main

import (
    "context"
    "fmt"
    "math/rand"
    "time"
)

const success = 0.1
const timeframe = time.Microsecond * 2

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

    do(ctx, cancel)
}

func do(ctx context.Context, cancel context.CancelFunc) {
    defer retry(ctx, cancel)

    select {
    case <-ctx.Done(): // timeout will be reached before i reach this line
        panic("fail")
    default:
        if rand.Float64() < success {
            cancel()
            fmt.Println("success")
            return
        } else {
            fmt.Println("fail")
    }
}

func retry(ctx context.Context, cancel context.CancelFunc) {
    r := recover()
    if r == nil {
        do(ctx, cancel)
    }
}

我不太用英语来谈论编程和技术,所以请随时要求重新措辞。


正确答案


您可以使用 this answer 中解释的构建标记技巧。

基本上创建 2 个文件,一个用于保存正常的超时值,另一个用于在 delve 下运行时保存较长的超时。

// +build delve

package main
import "time"

const timeframe = 10 * time.hour
// +build !delve

package main
import "time"

const Timeframe = 2 * time.Microsecond

调用 delve 时使用 --build-flags='-tags=delve' 选择正确的文件。

你根本做不到。

您要么必须将超时设置得足够大,以便可以进行手动调试,要么不使用调试器。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

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