Skip to main content

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) timeout for the game duration.
  • Two goroutines represent each player in the game. They continuously listen for the ball on the ball channel.
  • Each player waits for a random time (0-10 seconds) before serving the ball back to the other player.
  • The game ends after 2 minutes or when the context is canceled due to timeout.
  • The winner is determined by whoever has the ball at the end of the game.

Conclusion:

By building this ping pong game, we've demonstrated how goroutines, channels, and context can be used to create concurrent and well-controlled processes in Go. This example highlights the simplicity and elegance of Go's concurrency model, making it a preferred choice for building scalable and efficient applications.

Comments