added future

This commit is contained in:
Jian Han 2017-12-03 20:43:43 +10:00
parent 30c4b0d1c3
commit 56c9d0f669
2 changed files with 46 additions and 1 deletions

View File

@ -0,0 +1,45 @@
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
type data struct {
Body []byte
Error error
}
func futureData(url string) <-chan data {
c := make(chan data, 1)
go func() {
var body []byte
var err error
resp, err := http.Get(url)
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
c <- data{Body: body, Error: err}
}()
return c
}
func main() {
future := futureData("https://medium.com/@thejasbabu/concurrency-patterns-golang-5c5e1bcd0833")
future2 := futureData("https://golang.org/ref/mem")
// do many other things
body := <-future
fmt.Printf("response: %#v", "test")
fmt.Printf("error: %#v", body.Error)
body2 := <-future2
fmt.Printf("response: %#v", "test1")
fmt.Printf("error: %#v", body2.Error)
}

View File

@ -18,7 +18,7 @@ import (
) )
func main() { func main() {
lock := make(chan bool, 1) lock := make(chan bool, 2)
for i := 1; i < 7; i++ { for i := 1; i < 7; i++ {
go worker(i, lock) go worker(i, lock)
} }