如何为特定goroutine设置断点?

时间:2018-07-26 09:18:07

标签: go delve

我正在尝试调试一个简单的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

因此,结果为1的goroutine未被调试器击中。 如何在goroutine结果1中调试代码执行?

1 个答案:

答案 0 :(得分:3)

我在条件上使用了断点:

运行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