美文网首页
韩顺平 尚硅谷channel题(golang)

韩顺平 尚硅谷channel题(golang)

作者: FredricZhu | 来源:发表于2020-04-29 15:20 被阅读0次

作业1


image.png

作业2


image.png

作业1代码

package main

import (
    "fmt"
)

type Result struct {
    N   int
    Sum int
}

func MakeNumChan(ch chan int) {
    for i := 1; i <= 2000; i++ {
        ch <- i
    }

    close(ch)
}

func GetSum(n int, ch chan Result) {
    sum := 0
    for i := 1; i <= n; i++ {
        sum += i
    }

    res := Result{
        N:   n,
        Sum: sum,
    }
    ch <- res
}

func GetSumRange(numCh chan int, start int, end int, ch chan Result, exitCh chan int) {
    for i := start; i < end; i++ {
        n := <-numCh
        GetSum(n, ch)
    }
    exitCh <- 1
}

func main() {
    numCh := make(chan int, 2000)

    //启动协程输入1-2000的数
    go MakeNumChan(numCh)

    resCh := make(chan Result, 2000)

    exitCh := make(chan int, 8)

    //分8个协程计算和,并存入到resCh
    oneBatch := 2000 / 8
    for i := 0; i < 8; i++ {
        go GetSumRange(numCh, i*oneBatch, (i+1)*oneBatch, resCh, exitCh)
    }

    for {
        if len(exitCh) == 8 {
            close(exitCh)
            close(resCh)
            break
        }
    }

    for v := range resCh {
        fmt.Printf("res[%v]=%v\n", v.N, v.Sum)
    }

}

作业2-1代码

package main

import (
    "bufio"
    "fmt"
    "io"
    "log"
    "math/rand"
    "os"
    "sort"
    "strconv"
    "strings"
    "time"
)

func WriteDataToFile(fileIndex int, writeOkCh chan int) {
    fileName := fmt.Sprintf("D:/files/%v.txt", fileIndex)
    f, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY, 0666)

    if err != nil {
        log.Fatalf("打开文件失败, %v!!\n", err)
    }

    defer f.Close()

    rand.Seed(int64(time.Now().Nanosecond()))

    for i := 0; i < 1000; i++ {
        ele := rand.Intn(1000)
        s := fmt.Sprintf("%v\n", ele)
        f.WriteString(s)
    }

    writeOkCh <- 1
}

func Sort(fileIndex int, sortOkCh chan int) {
    fileName := fmt.Sprintf("D:/files/%v.txt", fileIndex)
    f, err := os.Open(fileName)
    if err != nil {
        log.Fatalf("打开文件失败, %v!!\n", err)
    }
    defer f.Close()

    reader := bufio.NewReader(f)

    intArr := make([]int, 0)
    for {
        str, err := reader.ReadString('\n')
        if err == io.EOF {
            break
        }
        str = strings.ReplaceAll(str, "\n", "")
        ele, err := strconv.Atoi(str)
        if err != nil {
            log.Fatalf("转换数字失败, %v!!\n", err)
        }
        intArr = append(intArr, ele)
    }

    fmt.Println("len of intArr: ", len(intArr))

    sort.Ints(intArr)

    wFileName := fmt.Sprintf("D:/files/2%v.txt", fileIndex)
    wf, err := os.OpenFile(wFileName, os.O_CREATE|os.O_WRONLY, 0666)
    if err != nil {
        log.Fatalf("打开文件失败, %v!!\n", err)
    }
    defer wf.Close()

    for _, val := range intArr {
        s := fmt.Sprintf("%v\n", val)
        wf.WriteString(s)
    }

    sortOkCh <- 1
}

func main() {
    writeOkCh := make(chan int, 10)
    for i := 1; i <= 10; i++ {
        go WriteDataToFile(i, writeOkCh)
    }

    for i := 0; i < 10; i++ {
        <-writeOkCh
    }

    sortOkCh := make(chan int, 10)

    for i := 1; i <= 10; i++ {
        go Sort(i, sortOkCh)
    }

    for i := 0; i < 10; i++ {
        <-sortOkCh
    }
}

相关文章

网友评论

      本文标题:韩顺平 尚硅谷channel题(golang)

      本文链接:https://www.haomeiwen.com/subject/fmtnwhtx.html