go协程练习题

开10个协程writeDataToFile,每个协程随机生成1000个数据,存放到10文件中
当10个文件都生成了,让10个sort协程从10文件中读取1000个数据,并完成排序,重新写入到10个结果文件

package main

import (
	"bufio"
	"io"
	"math/rand"
	"os"
	"strconv"
	"strings"
)

/**
写入字符串到文件中
*/
func writeFile(name string, str string) {
	f, _ := os.OpenFile(name, os.O_WRONLY|os.O_CREATE, 0666)
	defer func(f *os.File) {
		err := f.Close()
		if err != nil {

		}
	}(f)
	writer := bufio.NewWriter(f)
	_, err := writer.WriteString(str)
	if err != nil {
		return
	}
	err = writer.Flush()
	if err != nil {
		return
	}
}

func writeDataToFile(exitChan chan bool, index int) {
	var str string
	for i := 0; i < 1000; i++ {
		v := rand.Int()
		str += strconv.Itoa(v) + "\n"
	}
	writeFile("src"+strconv.Itoa(index)+".txt", str)
	exitChan <- true
}

/**
冒泡排序
*/
func bubbleSort(arr *[1000]int) {
	for i := 0; i < len(*arr); i++ {
		for j := 0; j < len(*arr)-i-1; j++ {
			if (*arr)[j] > (*arr)[j+1] {
				temp := (*arr)[j]
				(*arr)[j] = (*arr)[j+1]
				(*arr)[j+1] = temp
			}
		}
	}
}

func sort(exitChan chan bool, index int) {
	f, _ := os.OpenFile("src"+strconv.Itoa(index)+".txt", os.O_RDONLY, 0666)
	defer func(f *os.File) {
		err := f.Close()
		if err != nil {

		}
	}(f)
	reader := bufio.NewReader(f)
	var arr [1000]int
	arrIndex := 0
	for {
		str, err := reader.ReadString('\n')
		if err == io.EOF {
			break
		}
		str = strings.TrimSuffix(str, "\n")
		rs, _ := strconv.Atoi(str)
		arr[arrIndex] = rs
		arrIndex++
	}
	bubbleSort(&arr)
	var str2 string
	for i := 0; i < len(arr); i++ {
		str2 += strconv.Itoa(arr[i]) + "\n"
	}
	writeFile("dest"+strconv.Itoa(index)+".txt", str2)
	exitChan <- true
}

func main() {
	exitChan := make(chan bool, 10)
	for i := 0; i < 10; i++ {
		go writeDataToFile(exitChan, i)
	}
	for i := 0; i < 10; i++ {
		<-exitChan
	}
	for i := 0; i < 10; i++ {
		go sort(exitChan, i)
	}
	for i := 0; i < 10; i++ {
		<-exitChan
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值