/**************************************************** MAIN ************************************************************/
// Function main is the entry point for the application and is responsible for configuring its environment.
func main() {
// Variable wg is main's WaitGroup, which detects when all of the goroutines that were launched have completed.
var wg sync.WaitGroup
// Start our timer...
start := time.Now()
// Create the channel that will be used by the file reader and file write goroutines.
ch := make(chan []byte, 4096)
// File Reading Goroutine
wg.Add(1)
go func(outch chan<- []byte) {
defer wg.Done()
// Open the file at kFromPath for reading...
file, ero := os.Open(kFromPath)
if ero != nil {
log.Fatal(ero)
return
}
// Automatically close the file when exiting this method.
defer file.Close()
// Cumulative counters
nBytes := uint64(0)
nChunks := uint64(0)
// The buffer for data that is read from the file.
buf := make([]byte, kMaxBufferSize)
// Loop through the file reading chunks of data, which is sent over the channel.
for {
n, err := file.Read(buf[:cap(buf)])
// Did we read any data from the file? Was there an error?
if n == 0 && err != io.EOF {
log.Fatal(err)
return
}
// Update the cumulative counters.
nChunks++
nBytes += uint64(len(buf))
// Send the data over the channel.
outch <- buf[:n]
}
// Signal to the receiving goroutines that there is no more data.
close(outch)
// When there is no more data to process, display the sender's status.
fmt.Printf("Recv:\t\tnBytes: %d, nChunks: %d\n", nBytes, nChunks)
}(ch)
// File Writing Goroutine.
wg.Add(1)
go func(inch <-chan []byte) {
defer wg.Done()
// Cumulative counters
nBytes := uint64(0)
nChunks := uint64(0)
// Create the output file.
file, erc := os.Create(kToPath)
if erc != nil {
log.Fatal(erc)
return
}
// Automatically close the file when exiting this method.
defer file.Close()
// While there is data to read in the channel, we will get it and writing it to the output file.
for buf := range inch {
// Determine the length of the chunk of data that is available.
bytesRead := len(buf)
// Write the chunk to the output file.
file.Write(buf[:bytesRead])
// Update the cumulative counters...
nBytes += uint64(bytesRead)
nChunks++
}
// When there is no more data to process, display the receiver's status.
fmt.Printf("Sent:\t\tnBytes: %d, nChunks: %d\n", nBytes, nChunks)
}(ch)
// Wait here until all goroutines have completed their work.
wg.Wait()
// Show the duration.
fmt.Printf("Elapsed: %s", time.Since(start))
}
-j
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.