Sobes.tech
Senior

Task: "Ping-pong with timeout" Write a function pingPong that: - Starts two goroutines: one generates "ping" messages, the other — "pong". - Goroutines should exchange messages through a shared channel strictly in turn. - The exchange continues for 3 seconds, after which the program should terminate (graceful shutdown). - Use context for cancellation via timeout. - Output each message on the screen along with the time (in milliseconds from start). Example of expected output: 0ms: ping

sobes.tech AI

Answer from AI

go package main

import ( "context" "fmt" "time" )

func pingPong() { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel()

ch := make(chan string)
start := time.Now()

// Function to print message with elapsed time
printMsg := func(msg string) {
	elapsed := time.Since(start).Milliseconds()
	fmt.Printf("%dms: %s\n", elapsed, msg)
}

// Goroutine for ping
go func() {
	for {
		select {
		case <-ctx.Done():
			return
		case ch <- "ping":
		}
	}
}()

// Goroutine for pong
go func() {
	for {
		select {
		case <-ctx.Done():
			return
		case msg := <-ch:
			printMsg(msg)
			if msg == "ping" {
				ch <- "pong"
			}
		}
	}
}()

// Main goroutine reads pong and prints
for {
	select {
	case <-ctx.Done():
		return
	case msg := <-ch:
		printMsg(msg)
	}
}

}

func main() { pingPong() }


In this solution, two goroutines exchange messages through the channel `ch`. The `ping` goroutine sends "ping", the `pong` goroutine reads "ping", prints it, and sends "pong" back. The main goroutine reads "pong" and prints it. The context with a 3-second timeout ensures a graceful shutdown.
Task: "Ping-pong with timeout" Write a function… - sobes.tech