Golang : GoRoutine Ping-Pong (Alternating Execution)

Problem: Ping-Pong (Alternating Execution)

Task: Spawn two goroutines (ping and pong) that strictly alternate printing “ping” and “pong” N times each, before exiting cleanly without sleeping.



package main                                                                                                                                             

import (
    "fmt"
    "sync"
)

func main() {
    const rounds = 5 
    pingCh := make(chan struct{})
    pongCh := make(chan struct{})
    var wg sync.WaitGroup
    wg.Add(2)

    go func() {
       defer wg.Done()
       for i := 0; i < rounds; i++ {
           <-pingCh
           fmt.Println("Ping")
           pongCh <- struct{}{}
       }
    }() 

    go func() {
       defer wg.Done()
       for i := 0; i < rounds; i++ {
          <-pongCh
          fmt.Println("Pong")
          // First ping has already been pushed in main
          if i < rounds-1 {
             pingCh <- struct{}{}
          }
       }
    }() 

    pingCh <- struct{}{}
    wg.Wait()
}

Output

# go run -race main.go
Ping
Pong
Ping
Pong
Ping
Pong
Ping
Pong
Ping
Pong


ยฉ 2019-2026 Algotree.org | All rights reserved.

This content is provided for educational purposes. Feel free to learn, practice, and share knowledge.
For questions or contributions, visit algotree.org

"Simplicity is the ultimate sophistication. - Leonardo da Vinci"