27.Go语言·协程Goroutine·管道Channel(一)

2019-06-11  本文已影响0人  一枼落知天下

main.go

// Go语言·协程Goroutine·管道Channel
package main


import (
    model "day31/model"
)

var content string = `
————————————————Go语言·协程Goroutine·管道Channel————————————————————
一、协程&管道双剑合璧
`




func main() {
    model.ExpGoroutine()
}

model/Single.go

package model

import (
    "fmt"
    "sort"
)

/**
 * [Single 启动协程读写管道中数据]
 * @author Jhou Shuai
 * @datetime 2019-06-11T19:42:36+0800
 */
func Single() {
    var intChan chan int = make(chan int, 50)
    // 标志位管道,
    var flagChan chan bool = make(chan bool, 1)

    go writeData(intChan, cap(intChan))
    go readData(intChan, flagChan)

    for {
        _, ok := <-flagChan
        if !ok {
            break
        }
    }
}

func writeData(intChan chan int, n int) {
    for i := 1; i <= n; i++ {
        intChan <- i
        fmt.Printf("writeData[数据] %v \n", i)
    }
    close(intChan)
}

func readData(intChan chan int, flagChan chan bool) {
    for {
        v, ok := <-intChan
        if !ok {
            break
        }
        fmt.Printf("readData[数据] %v \n", v)
    }
    flagChan <- true
    close(flagChan)
}

/**
 * [ExpGoroutine 启动多个协程]
 * 启动协程读写管道中数据
 * @author Jhou Shuai
 * @datetime 2019-06-11T19:42:25+0800
 */
func ExpGoroutine() {
    // 启动协程数目
    var num int = 20
    // 初始化一个整数管道
    numChan := make(chan int, 2000)
    // 初始化一个map管道,用于存放计算结果
    resChan := make(chan map[int]int, cap(numChan))
    done := make(chan bool, num)
    // 存储计算结果
    myMap := make(map[int]int)
    // 存储map的key进行排序,升序
    myslice := make([]int, cap(numChan))

    // 开启写入数据协程
    go writeData(numChan, cap(numChan))

    // 开启多个读取数据协程
    for i := 0; i < num; i++ {
        go getResult(numChan, resChan, done)
    }

    go func() {
        for i := 0; i < num; i++ {
            <-done
        }
        close(resChan)
    }()

    //通过resChan管道获取数据
    for {
        v, ok := <-resChan
        if !ok {
            break
        }
        for key, val := range v {
            myMap[key] = val
            myslice[key-1] = key
        }
    }

    // 升序
    sort.Ints(myslice)
    // 输出结果
    for _, v := range myslice {
        fmt.Printf("res[%v]=%v \n", v, myMap[v])
    }
}

func getResult(intChan chan int, resChan chan map[int]int, done chan bool) {
    for {
        val, ok := <-intChan
        if !ok {
            break
        }
        fmt.Printf("readData[数据] %v \n", val)
        sum := 0
        for i := 1; i <= val; i++ {
            sum += i
        }
        res := make(map[int]int, 1)
        res[val] = sum
        resChan <- res
    }
    done <- true
}

上一篇下一篇

猜你喜欢

热点阅读