Skip to content

Checkpoint: Validate in Parallel, Report in Order

The Course
•
30 min study

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. f returns 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

  1. Write mapConcurrent from memory, then compare it with the last lesson.
  2. Write checkRecord(text string) error, which accepts ITEM:QUANTITY with a quantity from 1 to 1000.
  3. Write validateAll(ctx context.Context, records []string) error, which runs checkRecord on the pool and joins the errors in input order, each wrapped with its record number.
  4. Check a list with two bad records, a clean list, and a cancelled context.
  5. 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!: jobs is never closed, or the function returns before closing it on the cancelled path.
  • The cancelled run returns some results: the function returns results when the loop ends instead of checking ctx.Err() after Wait.
  • A plain break inside the select only leaves the select, so the loop keeps trying to send after cancellation.
  • Record numbers start at 0: wrap each error with i + 1.
Exercise

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:

Text
record 2: "drill:0": quantity must be 1-1000; record 3: "lamp": use ITEM:QUANTITY
all records valid
context canceled
Your working space Go
package 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
Run the solution Go
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))
}
Text
record 2: "drill:0": quantity must be 1-1000; record 3: "lamp": use ITEM:QUANTITY
all records valid
context canceled

checkRecord 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.

Was this article helpful?

Your response is saved on this device.