This checkpoint is the project's pipeline in miniature. Records are checked concurrently by a fixed number of workers, each problem is reported at its record's position, and a cancelled context stops the whole run with nothing reported. You will write the pool yourself this time, then use it, and prove that its output never depends on which worker happened to finish first.
What you will use
- A generic pool with a context.
mapConcurrent[T, R any](ctx, items, workers, f) ([]R, error)as in the last lesson, with jobs that carry their index. - Errors as results.
freturns a struct holding the record's error, so a bad record does not stop the pool. - A labelled break and a final
ctx.Err()check, so cancellation always produces an error and no partial results. - Errors joined in order. Collect the per-record errors by index and combine them with
errors.Join.
Plan before you type
- Write
mapConcurrentfrom memory, then compare it with the last lesson. - Write
checkRecord(text string) error, which acceptsITEM:QUANTITYwith a quantity from 1 to 1000. - Write
validateAll(ctx context.Context, records []string) error, which runscheckRecordon the pool and joins the errors in input order, each wrapped with its record number. - Check a list with two bad records, a clean list, and a cancelled context.
- Run your program several times. The output must never change.
Prove the order does not depend on timing
Make the pool use 1 worker, then 3, then 50. The output must be identical each time. If it changes, results are being collected in completion order instead of by index.
Mistakes worth checking for
all goroutines are asleep - deadlock!:jobsis never closed, or the function returns before closing it on the cancelled path.- The cancelled run returns some results: the function returns
resultswhen the loop ends instead of checkingctx.Err()afterWait. - A plain
breakinside theselectonly leaves theselect, so the loop keeps trying to send after cancellation. - Record numbers start at 0: wrap each error with
i + 1.
Your turn
Write mapConcurrent and validateAll as described, using three workers. Check tent:2 drill:0 lamp hat:5, then tent:1 drill:1000, then the first list again with a context that is already cancelled. Print each result on one line.
The output should be:
record 2: "drill:0": quantity must be 1-1000; record 3: "lamp": use ITEM:QUANTITY
all records valid
context canceledpackage main
func main() {
// Write mapConcurrent, checkRecord and validateAll, then check three runs.
}Hint 1: the idea
validateAll has two kinds of failure: records with problems, which it joins, and cancellation, which it returns as it is. Check for cancellation first.
Hint 2: a first step
Let f be func(text string) error { return checkRecord(text) }, so R is error. Then loop over the results and append fmt.Errorf("record %d: %w", i+1, err) for each non-nil one.
Worked solution
package main
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"sync"
)
func mapConcurrent[T, R any](ctx context.Context, items []T, workers int, f func(T) R) ([]R, error) {
workers = max(1, min(workers, len(items)))
results := make([]R, len(items))
jobs := make(chan int)
var wg sync.WaitGroup
for range workers {
wg.Add(1)
go func() {
defer wg.Done()
for i := range jobs {
results[i] = f(items[i])
}
}()
}
send:
for i := range items {
select {
case jobs <- i:
case <-ctx.Done():
break send
}
}
close(jobs)
wg.Wait()
if err := ctx.Err(); err != nil {
return nil, err
}
return results, nil
}
func checkRecord(text string) error {
_, quantity, ok := strings.Cut(text, ":")
if !ok {
return fmt.Errorf("%q: use ITEM:QUANTITY", text)
}
if n, err := strconv.Atoi(quantity); err != nil || n < 1 || n > 1000 {
return fmt.Errorf("%q: quantity must be 1-1000", text)
}
return nil
}
func validateAll(ctx context.Context, records []string) error {
results, err := mapConcurrent(ctx, records, 3, checkRecord)
if err != nil {
return err
}
var problems []error
for i, err := range results {
if err != nil {
problems = append(problems, fmt.Errorf("record %d: %w", i+1, err))
}
}
return errors.Join(problems...)
}
func show(err error) {
if err == nil {
fmt.Println("all records valid")
return
}
fmt.Println(strings.ReplaceAll(err.Error(), "\n", "; "))
}
func main() {
records := strings.Fields("tent:2 drill:0 lamp hat:5")
show(validateAll(context.Background(), records))
show(validateAll(context.Background(), strings.Fields("tent:1 drill:1000")))
ctx, cancel := context.WithCancel(context.Background())
cancel()
show(validateAll(ctx, records))
}record 2: "drill:0": quantity must be 1-1000; record 3: "lamp": use ITEM:QUANTITY
all records valid
context canceledcheckRecord already has the type func(string) error, so it is passed directly. The two problems appear in input order whatever the scheduling, drill:1000 checks the upper bound, and the cancelled run reports only the cancellation.
Completion is saved in this browser only. It does not measure mastery.