Skip to main content

Posts

Showing posts with the label golang-exercise

Learn Concurrency in Go: A Practical Exercise with Goroutines, Channels, and Context

Just for fun, we will create some basic ping pong game where two users are represented by two goroutines. We will explore how concurrency works in Go, understand the communication between two routines, and learn about the usage of context. Exercise: Implement a ping pong game using channels and goroutines. Two players will participate in the game, each represented by a goroutine. The game will continue for a duration of 2 minutes. Players will take turns holding the ball, waiting for a random time (0-10 seconds), and then serving it back. Each player serves at random intervals, adding an element of unpredictability to the game. At the end of the 2-minute period, the player holding the ball is declared the winner. Context and goroutines will be utilized to manage the game's duration and execution. Solution : Explanation: We create a buffered channel ball to simulate the movement of the ball between players. Using context.WithTimeout, we define a 120-second(2 min) time...