goruntine+channel 案例练习2

package main
import (
	"fmt"
	"math/rand"
	"time"
	"bufio"
	"os"
	"sort"
)


func main(){
	//状态通道
	writeDataOK := make(chan bool,1)

	rand.Seed(time.Now().UnixNano())
	

	filePath:="d:/mydatatest.txt"

	go func(filePath string,writeDataOK chan bool){
		
		file,OpenFileErr:=os.OpenFile(filePath,os.O_WRONLY|os.O_CREATE,0666)
		if OpenFileErr != nil{
			panic(OpenFileErr)
		}

		defer file.Close()
		
		writer:=bufio.NewWriter(file)
		for i:=0;i<1000;i++{
			//写入随机字符	
			writer.WriteString(string(rand.Int63n('z'-'A') + 'A')) 
		}
		
		writer.Flush()
		fmt.Printf("写入文件 名称%v \n",filePath)

		
		writeDataOK<-true //!
	}(filePath,writeDataOK)

	

		for;;{
			if len(writeDataOK) == 1{
				fmt.Println("协程完成工作了")
				close(writeDataOK)
				break
			}
		}


	dataChan:=make(chan string, 1) //字符串管道 1个够了
	readOK:=make(chan bool,1)



	
	go func(filePath string, readOK chan bool){
		//读出文件
		file,OpenFileErr:=os.OpenFile(filePath,os.O_RDONLY,0666)
		if OpenFileErr != nil{
			panic(OpenFileErr)
		}

		defer file.Close()

		reader:=bufio.NewReader(file)
		//遍历文件 fileByte,_:reader.ReadByte() 取出fileByte 到 int slice 中 
		fileSlice := []int{}
		for i:=0;i<1000;i++{
			fileByte,_:=reader.ReadByte()
			fileSlice = append(fileSlice,int(fileByte)) 
		}

		//排序
		sort.Ints(fileSlice)

		str:=""
		for i:=0;i<len(fileSlice);i++{
			str+=string(byte(fileSlice[i]))//字符串拼接
		}
		dataChan<- str
		readOK<- true
		fmt.Println("文件信息存入完成")
	}(filePath,readOK)
	
	for;;{
		if len(readOK) == 1{
			fmt.Println("协程任务完成~")
			close(dataChan)
			close(readOK)
			break
		}
	}
		
	//存入文件
	
	RewirteOK:=make(chan bool,1)
	newfilePath:="d:/mydatatest(Ints).txt"

	
	go func(newfilePath string,RewirteOK chan bool){
		file,OpenFileErr:=os.OpenFile(newfilePath,os.O_WRONLY|os.O_CREATE,0666)
		
		if OpenFileErr != nil{
			panic(OpenFileErr)
		}
		defer file.Close()

		writer:=bufio.NewWriter(file)
			str:= <-dataChan
		writer.WriteString(str)	
		writer.Flush()

		RewirteOK<-true
		fmt.Printf("排序后的文件 %v",newfilePath)
	}(newfilePath,RewirteOK)


	for;;{
		if len(RewirteOK)==1{
			fmt.Println("协程任务完成~~")
			close(RewirteOK)
			break
		}
	}
	

}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值