2

我正在尝试调试一个简单的 golang 程序,但不知道如何在delve调试器中的特定 goroutine 上设置断点。

这是一个例子:

package main

import "fmt"

func adder(a int, b int, res_chan chan int) {
    c := a + b
    res_chan <- c
}

func main() {
    chan1 := make(chan int)
    chan2 := make(chan int)

    go adder(0, 1, chan1)
    go adder(0, 2, chan2)

    res1 := <-chan1
    res2 := <-chan2

    fmt.Printf("Channel 1: %d\nChannel 2: %d\n", res1, res2)
}

我这样做dlv debug

Type 'help' for list of commands.

在 goroutine 上设置断点,在这里我直观地假设调试器将停止两次(在每个调用的 goroutine 上):

(dlv) b main.adder
Breakpoint 1 set at 0x49dd1f for main.adder() ./adder.go:5
(dlv) c
> main.adder() ./adder.go:5 (hits goroutine(18):1 total:2) (PC: 0x49dd1f)
> main.adder() ./adder.go:5 (hits goroutine(19):1 total:2) (PC: 0x49dd1f)
     1: package main
     2:
     3: import "fmt"
     4:
=>   5: func adder(a int, b int, res_chan chan int) {
     6:         c := a + b
     7:         res_chan <- c
     8: }
     9:
    10: func main() {
(dlv) s
> main.adder() ./adder.go:6 (PC: 0x49dd2d)
     1: package main
     2:
     3: import "fmt"
     4:
     5: func adder(a int, b int, res_chan chan int) {
=>   6:         c := a + b
     7:         res_chan <- c
     8: }
     9:
    10: func main() {
    11:         chan1 := make(chan int)
(dlv) 
> main.adder() ./adder.go:7 (PC: 0x49dd3c)
     2:
     3: import "fmt"
     4:
     5: func adder(a int, b int, res_chan chan int) {
     6:         c := a + b
=>   7:         res_chan <- c
     8: }
     9:
    10: func main() {
    11:         chan1 := make(chan int)
    12:         chan2 := make(chan int)

检查c变量的值:

(dlv) p c
2

继续执行:

(dlv) c
Channel 1: 1
Channel 2: 2
Process 8112 has exited with status 0

退出调试器:

(dlv) q
Process 8112 has exited with status 0

因此,带有结果的 goroutine1没有被调试器击中。如何在 goroutine 结果中调试代码执行1

4

1 回答 1

5

我已经使用条件断点:

运行dlv debug

Type 'help' for list of commands.

在一行上设置断点,其中 goroutine 可以通过某些条件来识别。在线7变量c将已经被评估,因此我们可以在其上建立一个条件。

在第 7 行设置断点:

(dlv) b adder.go:7
Breakpoint 1 set at 0x49dd3c for main.adder() ./adder.go:7

列出所有断点以确保清晰:

(dlv) breakpoints
Breakpoint unrecovered-panic at 0x42a870 for runtime.startpanic() /home/dmytriv/.soft/go/src/runtime/panic.go:591 (0)
        print runtime.curg._panic.arg
Breakpoint 1 at 0x49dd3c for main.adder() ./adder.go:7 (0)

设置断点条件1

(dlv) cond 1 c == 1

继续执行:

(dlv) c

这里断点被击中:

> main.adder() ./adder.go:7 (hits goroutine(5):1 total:1) (PC: 0x49dd3c)
     2:
     3: import "fmt"
     4:
     5: func adder(a int, b int, res_chan chan int) {
     6:         c := a + b
=>   7:         res_chan <- c
     8: }
     9:
    10: func main() {
    11:         chan1 := make(chan int)
    12:         chan2 := make(chan int)

检查c变量的值:

(dlv) p c
1

继续:

(dlv) c
Channel 1: 1
Channel 2: 2
Process 10096 has exited with status 0

退出调试器:

(dlv) q
Process 10096 has exited with status 0
于 2018-07-26T09:18:07.307 回答