Go语言 协程配合管道的综合案例-1

1.编写协程配合管道的综合案例-1

要求如下:
1)启动一个协程,将1-2000的数放到一个channel中,比如numChan
2) 启动八个协程,从numChan取出数(比如n),并计算1+…+n的值,并存放到resChan
3)最后八个协程协同完成工作后,再遍历resChan,并显示结果 [ 如 res[1]=1 … res[10]=55 … ]
4) 注意,考虑resChan chan int 是否合适?

2.代码如下:

	package main
	
	import (
	    "fmt"
	    "sync"
	)
	
	//定义一个wg,数据类型为WaitGrop,在关闭协程时,需要被用到
	var wg sync.WaitGroup
	
	//编写writeData函数
	func wtireData(intChan chan<- int) {
	    for i := 1; i <= 200; i++ {
	        intChan <- i
	    }
	    close(intChan)
	    wg.Done()
	}
	
	//编写sumData函数
	func sumData(intChan <-chan int, resChan chan<- map[int]int) {
	    for {
	        v, ok := <-intChan
	        if !ok {
	            break
	        }
	        //计算1+2+...n的值
	        sum := 0
	        for i := 1; i <= v; i++ {
	            sum += i
	        }
	        //将值发送至resChan
	        numSum := make(map[int]int)
	        numSum[v] = sum
	        resChan <- numSum
	    }
	    close(resChan)
	    wg.Done()
	}
	
	//编写readData函数遍历输出
	func readData(resChan <-chan map[int]int) {
	    for {
	        v, ok := <-resChan
	        if !ok {
	            break
	        }
	        for index, value := range v {
	            fmt.Printf("res[%v]=%v\n", index, value)
	        }
	    }
	    wg.Done()
	}
	
	//主函数
	func main() {
	    intChan := make(chan int, 10)
	    resChan := make(chan map[int]int, 10) //根据题目要求我们这里使用map存储计算的值
	        
	    //指定当前程序使用协程的个数,你启用多少就填多少,不能多也不能少
	    wg.Add(9) 
	    go wtireData(intChan)
	    //启用8个协程处理问题
	    for i := 1; i <= 8; i++ {
	        go sumData(intChan, resChan)
	        go readData(resChan)
	    }
	    wg.Wait()
	}

3.运行截图如下

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值