mirror of
https://github.com/crazybber/awesome-patterns.git
synced 2024-11-22 04:36:02 +03:00
added future
This commit is contained in:
parent
30c4b0d1c3
commit
56c9d0f669
45
concurrency/future/main.go
Normal file
45
concurrency/future/main.go
Normal 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)
|
||||
}
|
@ -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)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user