Last active
November 28, 2022 07:42
-
-
Save christophberger/2378d127b561c7f08332326cda205db8 to your computer and use it in GitHub Desktop.
Code from appliedgo.net/futures
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" | |
) | |
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