Created
April 18, 2016 10:31
-
-
Save gerbenjacobs/7dc637a73801c11c373757329608456c to your computer and use it in GitHub Desktop.
Golang Timeout with channels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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