Implementing Timeouts in Go Using Channels

GoGoBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

The purpose of this challenge is to implement timeouts in Go using channels and select.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Go`")) -.-> go/ConcurrencyGroup(["`Concurrency`"]) go/ConcurrencyGroup -.-> go/timeouts("`Timeouts`") subgraph Lab Skills go/timeouts -.-> lab-15443{{"`Implementing Timeouts in Go Using Channels`"}} end

Timeouts

When programs connect to external resources or need to bound execution time, timeouts are important. The challenge is to implement timeouts in Go using channels and select.

Requirements

  • Implement timeouts in Go using channels and select.
  • Use a buffered channel to prevent goroutine leaks in case the channel is never read.
  • Use time.After to await a value to be sent after the timeout.
  • Use select to proceed with the first receive that's ready.

Example

## Running this program shows the first operation timing
## out and the second succeeding.
$ go run timeouts.go
timeout 1
result 2

Summary

In this challenge, we learned how to implement timeouts in Go using channels and select. We used a buffered channel to prevent goroutine leaks in case the channel is never read, and time.After to await a value to be sent after the timeout. We also used select to proceed with the first receive that's ready.

Other Go Tutorials you may like