Ping Pong Goroutines Take Turns
Two goroutines trade turns across two unbuffered channels; every handoff is a rendezvous, so the printed ping and pong sequence is fully deterministic.
Code
package main
import (
"fmt"
"sync"
)
func main() {
pingCh := make(chan struct{})
pongCh := make(chan struct{})
const rounds = 3
var wg sync.WaitGroup
wg.Add(2)
// Two goroutines take turns:ping 先接 main 的发球,打完一拍交给 pong
go func() {
defer wg.Done()
for i := 1; i <= rounds; i++ {
<-pingCh
fmt.Println("ping", i)
pongCh <- struct{}{}
}
}()
// pong 最后一拍不再回传:ping 已退出循环,再发会永远阻塞
go func() {
defer wg.Done()
for i := 1; i <= rounds; i++ {
<-pongCh
fmt.Println("pong", i)
if i < rounds {
pingCh <- struct{}{}
}
}
}()
pingCh <- struct{}{} // main 发球
wg.Wait()
}How the code behaves
Ping Pong Goroutines Take Turns is built around the function main.
The loop for i := 1; i <= rounds; i++ is the only repeated construct. Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.
Applying it
The run prints ping, pong — each prefix names the step that produced it.
Statements that matter
pingCh <- struct{}{} // main 发球
pingCh := make(chan struct{})
pongCh := make(chan struct{})
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Ping Pong Goroutines Take Turns print when run?
- Run it as a complete program — the output lines carry labels such as `ping`, `pong`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.