我有一个简单的2文件访问应用程序。我正在尝试在2个频道上对ping和pong消息进行基准测试。
目标是运行基准测试以查看可以完成多少次来回乒乓球(这就是为什么我通过尝试,以便基准测试可以在不同的输入下继续运行)
出于某种原因,它仅在运行时显示:
go build
./main
输出:
ping
pong
ping
pong
ping
pong
ping
pong
ping
为什么这么少迭代就结束了?
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)
}
}
答案 0 :(得分:2)
fmt.Scanln
需要一个指针:
使用这个:
fmt.Println(fmt.Scanln(&input))
这对我有用:
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"
}
}
输出:
...
ping
pong 999
ping
pong 1000
1000
答案 1 :(得分:-1)
不起作用的原因是我将文件从main.go移到了ping.go。 当我进行构建时,它创建了另一个二进制名称./pingpong,但是我仍在运行旧的二进制文件!