Running several goroutines (WaitGroup, ErrGroup)

Managing a warehouse

Report a typo

You're managing a large warehouse. Various suppliers ship different items to your warehouse, and your job is to keep track of the number of products you have. To smoothen this process, you've decided to use a Go program.

Your job is to add each new product concurrently and print the result; to do this, you need to write the necessary code within the following methods:

Within the HandleNewProduct() function, you need to do the following:

  • Ensure the function notifies the wait group when it finishes its tasks.

  • Read from the input channel and parse the received product text as long as the channel remains open.

Within the ParseProductText() function, you need to do the following:

  • Parse the input string (e.g. "apple 5") into a product name and amount. If there's an issue (for instance, if you're unable to parse an amount), simply return an error.

Within the main() function:

  • Start the HandleNewProduct() function concurrently using the sync.WaitGroup.

  • Ensure every goroutine finishes before you close the sending channel. This channel is where you transmit your input.

Sample Input 1:

bread 10
apple 15
banana 20
apple 5
orange 3

Sample Output 1:

map[apple:20 banana:20 bread:10 orange:3]
Write a program in Go
package main

import (
"bufio"
"fmt"
"os"
"sync"
)

type Product struct {
Name string
Amount int
}

func HandleNewProduct(wg *sync.WaitGroup, inputChanel <-chan string, outputChannel chan<- Product) {
// TODO: Ensure that the goroutine is finished before exiting the program
defer wg.?()

// TODO: read from the input channel and parse the product text while the channel is open
for productText := ? {
productName, amount, err := ParseProductText(productText)
if err != nil {
panic(err)
}
outputChannel <- Product{Name: productName, Amount: amount}
}
}

func ParseProductText(input string) (string, int, error) {
// TODO: Parse the input string into a product name and amount
// The input string should be in the format: <name:string> <amount:int>.
// For example: "apple 5"

???

return productName, amount, nil

Create a free account to access the full topic