ZhangZhihui's Blog  

 

复制代码
package main

import (
    "fmt"
    "sync"
    "time"
)

var workers = 3

func processItem(input <-chan int, output chan<- int, wg *sync.WaitGroup) {
    for {
        fmt.Println("=")
        in := <-input
        fmt.Printf("Working on input: %v\n", in)
        output <- in + 1
        wg.Done()
    }
}

func main() {
    items := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

    var wg sync.WaitGroup
    wg.Add(len(items))
    out := make(chan int, len(items))
    in := make(chan int)

    for i := 0; i < workers; i++ {
        go processItem(in, out, &wg)
    }

    for _, val := range items {
        in <- val
    }

    wg.Wait()

    total := 0
    for j := 0; j < len(items); j++ {
        total += <-out
    }
    fmt.Printf("Total sum is : %v\n", total)

    time.Sleep(20 * time.Second)
}
复制代码

 

复制代码
zzh@ZZHPC:/zdata/Github/ztest$ go run main.go
=
Working on input: 1
=
Working on input: 2
=
Working on input: 3
=
Working on input: 4
=
Working on input: 5
=
Working on input: 6
=
Working on input: 7
=
Working on input: 8
=
Working on input: 9
=
Working on input: 10
=
Total sum is : 65
=
=
复制代码

 

"Working on input"输出有10个,"="输出有13个,函数processItem中的for循环执行到语句“in := <-input”,其一直在等待数据,该程序运行了20s,主进程结束,for循环所在的子进程被强行中止。

posted on   ZhangZhihuiAAA  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
 
点击右上角即可分享
微信分享提示