~$ 存档

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

 

package main

import (
    "log"
    "sync"
    "time"
)

func main() {
    block := 12     //分块数,可以调整测试
    N := 1000000000 //最大数

    ch := make(chan int, block)
    exit := make(chan int)
    var wd sync.WaitGroup
    wd.Add(block)

    now := time.Now()

    for i := 0; i < block; i++ {
        n := i
        go func() {
            defer wd.Done()
            block_sum := 0
            start, end := (N+1)*n/block, (N+1)*(n+1)/block
            log.Println("n=", n, "start=", start, "end=", end)
            for j := start; j < end; j++ {
                block_sum += j
            }
            ch <- block_sum
        }()
    }
    go func() {
        sum := 0
        for block_sum := range ch {
            sum += block_sum
        }
        log.Println("channel关闭退出...")
        exit <- sum
    }()
    wd.Wait()
    log.Println("任务结束...")
    close(ch)

    log.Println("sum=", <-exit)
    log.Println("sec=", time.Since(now))

}

 

posted on 2021-02-15 02:44  LuoTian  阅读(219)  评论(0编辑  收藏  举报