package cos418_hw1_1 import ( "bufio" "io" "strconv" "sync" "os" ) // Sum numbers from channel `nums` and output sum to `out`. // You should only output to `out` once. // Do NOT modify function signature. func sumWorker(nums chan int, out chan int) { // TODO: implement me // HINT: use for loop over `nums` sum := 0 for num := range nums { sum += num } out <- sum close(out) } // Read integers from the file `fileName` and return sum of all values. // This function must launch `num` go routines running // `sumWorker` to find the sum of the values concurrently. // You should use `checkError` to handle potential errors. // Do NOT modify function signature. func sum(num int, fileName string) int { // TODO: implement me // HINT: use `readInts` and `sumWorkers` // HINT: used buffered channels for splitting numbers between workers file, err := os.Open(fileName) checkError(err) defer file.Close() numbers, err := readInts(file) checkError(err) chunk := len(numbers) / num input := make(chan int, num) output := make(chan int) var wg sync.WaitGroup for i := 0; i < num; i++ { start := i * chunk end := (i + 1) * chunk if i == num-1 { end = len(numbers) } wg.Add(1) go func(start, end int) { defer wg.Done() partialSum := 0 for j := start; j < end; j++ { partialSum += numbers[j] } input <- partialSum }(start, end) } go func() { wg.Wait() close(input) }() go sumWorker(input, output) return <-output } // Read a list of integers separated by whitespace from `r`. // Return the integers successfully read with no error, or // an empty slice of integers and the error that occurred. // Do NOT modify this function. func readInts(r io.Reader) ([]int, error) { scanner := bufio.NewScanner(r) scanner.Split(bufio.ScanWords) var elems []int for scanner.Scan() { val, err := strconv.Atoi(scanner.Text()) if err != nil { return elems, err } elems = append(elems, val) } return elems, nil }