From 56c9d0f66942c21da611a461bcbbe3fe53af1ce7 Mon Sep 17 00:00:00 2001 From: Jian Han Date: Sun, 3 Dec 2017 20:43:43 +1000 Subject: [PATCH] added future --- concurrency/future/main.go | 45 ++++++++++++++++++++++++++++++++++++++ concurrency/locker/main.go | 2 +- 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 concurrency/future/main.go diff --git a/concurrency/future/main.go b/concurrency/future/main.go new file mode 100644 index 0000000..c538582 --- /dev/null +++ b/concurrency/future/main.go @@ -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) +} diff --git a/concurrency/locker/main.go b/concurrency/locker/main.go index da9b5d7..764434e 100644 --- a/concurrency/locker/main.go +++ b/concurrency/locker/main.go @@ -18,7 +18,7 @@ import ( ) func main() { - lock := make(chan bool, 1) + lock := make(chan bool, 2) for i := 1; i < 7; i++ { go worker(i, lock) }