我有一个小问题。我正在尝试从文件中读取程序,然后在另一个文件中写入完全相同的内容。我已经使它工作了,但是我发现如果我使用goroutines对其进行了一点修改,它应该会运行得更快。我将读写分为不同的功能,并试图使它们进行通信。他们似乎可以正常通信,但是写入功能似乎实际上并未在目标文件中写入任何内容。问题是,当我选择一个比简单的短文本文件大得多的文件时,它确实会写,但不是全部,它会丢失东西。谁能确切告诉我这怎么可能出错?我的代码在这里:
func main() {
// Creating channels
messages := make(chan byte)
status := make(chan bool)
finished := make(chan bool)
fmt.Printf("Reporting from main thread. Created the channels, go routines will follow.\n")
go readFileRoutine("file", messages, status, finished)
fmt.Printf("Reporting from main thread, readFileRoutine has been let go.\n")
go writeFileRoutine("destination", messages, status)
fmt.Printf("Reporting from main thread, writeFileRoutine has been let go. Waiting on status message\n")
<-finished
close(status)
fmt.Printf("Success!\n")
}
func readFileRoutine(filename string, messages chan byte, status chan bool, finished chan bool) {
file, err := os.Open(filename)
check(err)
buff := bufio.NewReader(file)
fmt.Printf("Reporting from readFileRoutine, initialised. Will start reading now!\n")
for {
byti, err := buff.ReadByte()
fmt.Printf("Read character %c\n", byti)
if err == io.EOF { //If EOF break for loop and finish off
readFinished = true
break
}
<-status // Waiting for status message from writeFileRoutine
messages <- byti //Putting next message on channel, then buffering next character
}
fmt.Printf("Reporting from readFileRoutine, finished reading and putting messages on channel, will now wait on writer to finish\n")
//fmt.Printf("Reporting from readFileRoutine, finished with reading. Closing file and messages channel now\n")
file.Close()
<-status
fmt.Printf("Reporting from readFileRoutine, moving on to closing messages channel. Received status from writer correctly!\n")
close(messages)
<-status
fmt.Printf("Reporting from readFileRoutine, closed messages channel, will report status on the finished channel.\n")
finished <- true
}
func writeFileRoutine(filename string, messages chan byte, status chan bool) {
file, err := os.Create(filename) // Creates a new file
check(err)
buf := bufio.NewWriter(file) //New file writer
fmt.Printf("Reporting from writeFileRoutine, initialised. Will start writing now!\n")
status <- true
for readFinished == false {
bit := <-messages // Wait for receiving
fmt.Printf("Received message %c\n", bit)
buf.WriteByte(bit)
fmt.Printf("Written byte %c\n", bit)
status <- true //Sending status to readFileRoutine, done writing and waiting for next character
}
fmt.Printf("Reporting from writeFileRoutine, read all messages from reader and put them in a file\n")
file.Close()
fmt.Printf("Reporting from writeFileRoutine, closed file, will put true on status channel and exit\n")
status <- true
}
正如Martin在评论中指出的,我只是忘记了Writer.Flush()函数。我将buf.Flush()紧接在buf.WriteByte(bit)之后,并对其进行了修复。