Skip to content

Instantly share code, notes, and snippets.

@christophberger
Last active November 28, 2022 07:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christophberger/2378d127b561c7f08332326cda205db8 to your computer and use it in GitHub Desktop.
Save christophberger/2378d127b561c7f08332326cda205db8 to your computer and use it in GitHub Desktop.
Code from appliedgo.net/futures
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan int)
fmt.Println("\nA simple future")
fmt.Println("---------------\n")
go func(input int, result chan<- int) {
fmt.Println("Calculating")
time.Sleep(1 * time.Second)
fmt.Println("done")
result <- input * 2
}(1, c)
var value int
fmt.Println("Waiting")
value = <-c
fmt.Println("got", value)
fmt.Println("\nReading the future multiple times")
fmt.Println("-----------------------------\n")
c2 := make(chan int)
go func(input int, res chan<- int) {
fmt.Println("Calculating")
time.Sleep(1 * time.Second)
for {
fmt.Println("Writing result")
res <- input * 4
}
}(1, c2)
fmt.Println("Waiting")
fmt.Println("got", <-c2)
fmt.Println("got", <-c2)
fmt.Println("\nReading with a timeout")
fmt.Println("-----------------------------\n")
c3 := make(chan int)
go func(input int, res chan<- int) {
fmt.Println("Calculating")
time.Sleep(2 * time.Second)
for {
fmt.Println("Writing result")
res <- input * 8
}
}(1, c3)
get := func(s int) (result int, timedout bool) {
select {
case result = <-c3:
return result, false
case <-time.After(time.Duration(s) * time.Second):
return 0, true
}
}
fmt.Println("Waiting")
result, timedOut := get(1)
if timedOut {
// Handle the timeout.
fmt.Println("Timed out")
return
}
fmt.Println(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment