使用简单的乒乓测试对渠道进行基准测试

I have a simple 2 file go application. I am trying to benchmark ping and pong messages on 2 channels.

The goal is to run the benchmark to see how many back and forth ping and pong can be done (that is why I am passing the attempts so the benchmark can keep running at different inputs)

For some reason locally it is only displaying this when I run it:

go build
./main

Output:

ping
pong
ping
pong
ping
pong
ping
pong
ping  

Why does it end after so little iterations?

main.go

package main

import (
    "fmt"
)

func main() {

    PingPong(1000)

    var input string
    fmt.Scanln(input)
    fmt.Println("done!")
}

ping.go

package main

import "fmt"

func PingPong(attempts int) {
    pingCh := make(chan string)
    pongCh := make(chan string)

    go pinger(pingCh, pongCh)
    go ponger(pingCh, pongCh, attempts)

    pingCh <- "ping"
}

func pinger(pingCh chan string, pongCh chan string) {
    for {
        _ = <-pingCh
        fmt.Println("ping")
        pongCh <- "pong"
    }
}

func ponger(pingCh chan string, pongCh chan string, attempts int) {
    counter := 0
    for {
        msg := <-pongCh
        fmt.Println(msg)
        counter++
        if counter == attempts {
            fmt.Println(counter)
            break
        }
        pingCh <- "ping"
    }
}

ping_test.go

package main

import "testing"

func benchmarkPingPong(i int, b *testing.B) {
    for n := 0; n < b.N; n++ {
        PingPong(n)
    }
}

fmt.Scanln needs a pointer:
Use this:

fmt.Println(fmt.Scanln(&input))

This works for me:

package main

import "fmt"

func main() {
    PingPong(1000)
    var input string
    fmt.Println(fmt.Scanln(&input))
    fmt.Println("done!")
}

func PingPong(attempts int) {
    pingCh := make(chan string)
    pongCh := make(chan string)

    go pinger(pingCh, pongCh)
    go ponger(pingCh, pongCh, attempts)

    pingCh <- "ping"
}

func pinger(pingCh chan string, pongCh chan string) {
    for {
        _ = <-pingCh
        fmt.Println("ping")
        pongCh <- "pong"
    }
}

func ponger(pingCh chan string, pongCh chan string, attempts int) {
    counter := 0
    for {
        msg := <-pongCh
        counter++
        fmt.Println(msg, counter)
        if counter == attempts {
            fmt.Println(counter)
            break
        }
        pingCh <- "ping"
    }
}

output:

...
ping
pong 999
ping
pong 1000
1000

The reason it wasn't working is that I moved the files out from main.go to ping.go. When I ran go build, it created different binary name ./pingpong but I was still running the old binary!