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
}
}
}
goruntine+channel 案例练习2
最新推荐文章于 2023-10-24 15:39:16 发布