我试图在主线程中读取一个图片文件,每次读写1024*4大小的buf,然后将读取的内容和当前读取的起点位置包装成一个job对象,然后开启一个goroutine,通过管道来获取主线程每次读取的job对象,然后将内容写到一个新的文件中,以达到拷贝该图片的效果。但是不知道为何无法实现。下面给出我的代码。![image.png]
![1.png](https://static.studygolang.com/220317/ea7745ec422938841169504f7362319e.png)
![2.png](https://static.studygolang.com/220317/2ff14566b633609434ff78508f97abcf.png)
![3.png](https://static.studygolang.com/220317/7541c28e1bbc857a8d7cb1b23a76cf87.png)
![4.png](https://static.studygolang.com/220317/c5dadc8dc85da8cc86f74af3d25c056c.png)
![5.png](https://static.studygolang.com/220317/30ec04433adb06c902a08c1ba5d7e52e.png)
package main
import (
"bufio"
"fmt"
"io"
"os"
)
type job struct {
buf []byte
index int64
}
func newJob(buf []byte, index int64) *job {
return &job{
buf: buf,
index: index,
}
}
func copyFile(writer *bufio.Writer, jobChan <-chan *job, done chan bool) {
for newJob := range jobChan {
n, err := writer.Write(newJob.buf)
if err != nil {
fmt.Printf("write file failed,err:%v\n", err)
return
}
err = writer.Flush()
if err != nil {
fmt.Printf("flush file failed,err:%v\n", err)
return
}
fmt.Printf("begin:%v,write success %v\n", newJob.index, n)
//done <- true
}
done <- true
}
func main() {
srcFile, err := os.Open("./girl.jpg")
if err != nil {
fmt.Printf("open srcFile failed,err:%v\n", err)
return
}
dstFile, err := os.OpenFile("./girl_bak.jpg", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0777)
if err != nil {
fmt.Printf("open dstFile failed,err:%v\n", err)
return
}
defer srcFile.Close()
defer dstFile.Close()
reader := bufio.NewReader(srcFile)
writer := bufio.NewWriter(dstFile)
done := make(chan bool)
Buf := make([]byte, 1024)
total := int64(0)
jobChan := make(chan *job)
go copyFile(writer, jobChan, done)
for {
n, err := reader.Read(Buf)
if err == io.EOF {
fmt.Printf("read file finish\n")
break
}
if err != nil {
fmt.Printf("read file failed.err:%v\n", err)
return
}
newJob := newJob(Buf[:n], total)
jobChan <- newJob
total += int64(n)
}
close(jobChan)
<-done
}
newJob:=newJob(Buf[:n],total)
这里有问题
Buf[:n]和Buf在底层使用的同一个数组,因此写数据和读数据在操作同一段缓存
#1
更多评论