golang goroutine间通信效率

69 阅读1分钟

问题:两个goroutine通过两个无缓冲通道来互相发送消息,每秒能最多维持多少次通信?

测试环境:

机器: MacBook m1 Pro (14英寸,2021年) go version go1.19.2 darwin/arm64

测试结果: 在我的mac m1 上空消息发送,每秒可发送300万次左右

代码:


package main

import (
   "fmt"
   "time"
)

func ping(ch1, ch2 chan struct{}, done chan bool) {
   count := 0
   start := time.Now()

   for {
      ch1 <- struct{}{} // 发送信号
      <-ch2             // 接收信号
      count++

      if time.Since(start) >= time.Second {
         fmt.Printf("完成 %d 次通信\n", count)
         done <- true
         return
      }
   }
}

func pong(ch1, ch2 chan struct{}) {
   for {
      <-ch1             // 接收信号
      ch2 <- struct{}{} // 发送信号
   }
}

func main() {
   ch1 := make(chan struct{})
   ch2 := make(chan struct{})
   done := make(chan bool)

   go pong(ch1, ch2)
   go ping(ch1, ch2, done)

   <-done
}