Skip to content

Instantly share code, notes, and snippets.

@gerbenjacobs
Created April 18, 2016 10:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerbenjacobs/7dc637a73801c11c373757329608456c to your computer and use it in GitHub Desktop.
Save gerbenjacobs/7dc637a73801c11c373757329608456c to your computer and use it in GitHub Desktop.
Golang Timeout with channels
package main
import (
"fmt"
"time"
)
var (
ch chan bool
timeoutSecs uint = 3
workSecs uint = 2
)
func main() {
timeoutChan := make(chan bool, 1)
ch = make(chan bool, 1)
go SlowProcessingWork(timeoutChan)
select {
case <-ch:
fmt.Println("The function worked")
case <-timeoutChan:
fmt.Println("Timeout!")
}
}
func SlowProcessingWork(timeoutChan chan bool) {
go timeout(timeoutChan)
time.Sleep(time.Duration(workSecs) * time.Second)
ch <- true
}
func timeout(timeoutChan chan bool) {
time.Sleep(time.Duration(timeoutSecs) * time.Second)
timeoutChan <- true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment