golang代码 future promise

 

    func longTimeRequest() <-chan int32 {
        r := make(chan int32)
        go func() {
        time.Sleep(time.Second * 3) // 模拟一个工作负载
        r <- rand.Int31n(100)
    }()
        return r
    }

    func sumSquares(a, b int32) int32 {
        return a*a + b*b
    }

    func main() {
        rand.Seed(time.Now().UnixNano())

        a, b := longTimeRequest(), longTimeRequest()
        fmt.Println(sumSquares(<-a, <-b))
    }

    --------------------------------------------------------------------------------

    func longTimeRequest(r chan<- int32)  {
        time.Sleep(time.Second * 3) // 模拟一个工作负载
        r <- rand.Int31n(100)
    }

    func sumSquares(a, b int32) int32 {
        return a*a + b*b
    }

    func main() {
        rand.Seed(time.Now().UnixNano())

        ra, rb := make(chan int32), make(chan int32)
        go longTimeRequest(ra)
        go longTimeRequest(rb)

        fmt.Println(sumSquares(<-ra, <-rb))

        //也可以只用一个channel:
        results := make(chan int32, 2)         // 缓冲与否不重要
        go longTimeRequest(results)
        go longTimeRequest(results)

        fmt.Println(sumSquares(<-results, <-results))
    }

 

posted @ 2020-05-27 20:31  是的哟  阅读(358)  评论(0编辑  收藏  举报