4

When debugging a program that makes use of say context.WithTimeout when you are not stepping through lines the clock keeps ticking, so before you can debug code piece that depends on given context, that context becomes done thus the code piece you are interested in debugging does not execute. For example in the following snippet I have to increase the timestamp value to be able to step through do() and retry() because otherwise timeout will be reached way before I can do it:

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)
    }
}

I haven't used English that much to talk about programming and tech so, feel free to ask to rephrase.

mcv_dev
  • 338
  • 3
  • 14
  • 7
    When debugging, it still uses the system clock to get the current time; you can't stop time from passing. Your approach of increasing the timeout while debugging is how I would solve this also. – Adrian Mar 07 '22 at 13:57
  • @Adrian Is there no way to substiture system clock just for the program that is being debugged? – mcv_dev Mar 07 '22 at 14:00
  • 1
    if you have to edit many timeout , I think you can check if you are debugging as in this [methods](https://stackoverflow.com/questions/47879070/how-can-i-see-if-the-goland-debugger-is-running-in-the-program) to make timeout for debug case. – MSH Mar 07 '22 at 15:14

2 Answers2

2

How to stop the time when not stepping through lines during debugging?

You simply cannot.

You either have to increase your timeouts so large that you can do your manual debugging or not use a debugger.

Volker
  • 40,468
  • 7
  • 81
  • 87
1

You can use the build tag trick explained in this answer.

Basically create 2 files, one to hold the normal timeout value and the other to hold a longer timeout when running under delve.

// +build delve

package main
import "time"

const Timeframe = 10 * time.Hour
// +build !delve

package main
import "time"

const Timeframe = 2 * time.Microsecond

Use --build-flags='-tags=delve' when calling delve to choose the correct file.