Deterministic barriers in concurrent tests
Deterministic barriers in concurrent tests
A test must observe a real event, not guess when a goroutine has run. A barrier is a synchronization point: one participant cannot proceed until another signals. Use channels to arrange a known starting state and completion. Sleeping does not establish a happens-before relation.
Create the files shown below in a fresh directory, then run go test -count=1 -v ./... there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples.
--- go.mod ---module example.test/lesson
go 1.23
--- lesson_test.go ---package lesson
import ( "testing")
func TestLesson(t *testing.T) { ready := make(chan struct{}) release := make(chan struct{}) done := make(chan int, 1) go func() { close(ready); <-release; done <- 42 }() <-ready select { case <-done: t.Fatal("completed before release") default: } close(release) if got := <-done; got != 42 { t.Fatalf("got %d", got) }}Closing ready proves the worker reached that point. The worker cannot send until release is closed. The nonblocking receive is meaningful because the barrier prevents completion, not because of an assumed schedule. In these small tests an outer go test -timeout=10s bounds accidental hangs.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonWait for multiple workers
--- go.mod ---module example.test/lesson
go 1.23
--- lesson_test.go ---package lesson
import ( "sync" "testing")
func TestLesson(t *testing.T) { start := make(chan struct{}) var wg sync.WaitGroup values := make(chan int, 3) for i := 1; i <= 3; i++ { wg.Add(1) go func(n int) { defer wg.Done(); <-start; values <- n }(i) } close(start) wg.Wait() close(values) sum := 0 for n := range values { sum += n } if sum != 6 { t.Fatalf("sum=%d", sum) }}The buffer can hold all three results, so waiting before draining cannot block the sends. The sum is independent of order. Never use an unsynchronized boolean as a readiness flag. In real tests design cleanup to release workers even on failure.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonTry it locally
Use a start channel and two workers sending 5 and 7; assert the sum is 12 without checking arrival order. Use a fresh module with the same go.mod shown above; run go test -count=1 -v ./...
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Concurrency testing 01: Deterministic barriers in concurrent tests
Check the lesson objective before moving on.
Why wait for ready before checking the blocked operation?
Why can the test wait before draining a three-element result buffer?