美文网首页Go
go的协程并发-channel消息机制

go的协程并发-channel消息机制

作者: letcoda | 来源:发表于2018-11-12 23:52 被阅读12次

    go的协程并发-channel消息机制

    方式一
    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        chs := make([]chan string, 10)
    
        for i := 0; i < 10 ; i++ {
            chs[i] = make(chan string)
            go count(chs[i], "foo", int64(i))
        }
    
        for i, _ := range(chs) {
            k := <-chs[i]
            fmt.Println(k)
        }
        fmt.Println("This is the end")
    }
    
    func count(ch chan string, str string, i int64) {
        str = str + fmt.Sprintf("%d", i)
        time.Sleep(time.Duration(i) * time.Second)
        ch <- str
    }
    
    方式二
    package main
    
    import (
        "fmt"
        "net/http"
        "io/ioutil"
        "time"
    )
    
    func main() {
        urls := []string{"http://httpbin.org/cookies", "http://httpbin.org/get","http://httpbin.org/post"}
        now := time.Now()
    
        ch := make(chan string)
        for i, _ := range urls {
            go getCon(ch, urls[i])
        }
    
        for _ = range urls{
            r := <-ch
            fmt.Println("------midware--------")
            fmt.Println(r)
        }
        fmt.Println(time.Since(now))
    }
    
    func getCon(ch chan string, url string) {
        resp, err := http.Get(url)
        if err != nil {
            ch <- err.Error()
        }
    
        defer resp.Body.Close()
        body, _ := ioutil.ReadAll(resp.Body)
        ch <- string(body[:])
        return
    }
    

    go-协程实现方案汇总

    相关文章

      网友评论

        本文标题:go的协程并发-channel消息机制

        本文链接:https://www.haomeiwen.com/subject/akghfqtx.html