韩顺平 尚硅谷channel题(golang)

FredricZhu · · 706 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

作业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(writeOkCh chan bool) {
    f, err := os.OpenFile("D:/files/1.txt", 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 <- true
    close(writeOkCh)
}

func Sort(sortOkCh chan bool) {
    f, err := os.Open("D:/files/1.txt")
    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)

    wf, err := os.OpenFile("D:/files/2.txt", 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 <- true
    close(sortOkCh)

}

func main() {
    writeOkCh := make(chan bool, 1)
    go WriteDataToFile(writeOkCh)

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

    sortOkCh := make(chan bool, 1)
    go Sort(sortOkCh)
    for {
        _, ok := <-sortOkCh
        if !ok {
            break
        }
    }
}

作业2-2代码

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 {
        if len(writeOkCh) == 10 {
            close(writeOkCh)
            break
        }
    }

    sortOkCh := make(chan int, 10)

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

    for {
        if len(sortOkCh) == 10 {
            close(sortOkCh)
            break
        }
    }
}

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:FredricZhu

查看原文:韩顺平 尚硅谷channel题(golang)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

706 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传