golang协程与无缓冲信道

2020-03-14  本文已影响0人  飞翔的橙子哥
package main

import (
    "fmt"
    "math"
    "time"
)

var res = make(chan float64)

func timeCost(start time.Time) {
    tc := time.Since(start)
    fmt.Printf("time cost = %v\n", tc)
}

func calculate(n int) {
    defer timeCost(time.Now())
    pi := 0.0
    for i := 0; i < n; i++ {
        var k = float64(i)
        pi += 1.0 / math.Pow(16, k) * (4.0/(8.0*k+1.0) - 2.0/(8.0*k+4.0) - 1.0/(8.0*k+5.0) - 1.0/(8.0*k+6.0))
    }
    res <- pi
}

func main() {
    defer func() {
        fmt.Println("Total cost in main")
        timeCost(time.Now())
    }()
    startT := time.Now()
    count := 50

    for i := 0; i < count; i++ {
        go calculate(20000 + i*1000)
        // calculate(20000 + i*100)
    }

    for i := 0; i < count; i++ {
        <-res
    }
    fmt.Println("main ends")
    tc := time.Since(startT)
    fmt.Printf("time cost = %v\n", tc)
}

对于计算密集型任务,不宜开太多协程

上一篇下一篇

猜你喜欢

热点阅读