Sentinel Value Stops Workers

A reserved sentinel job value makes a worker exit early, and closing the jobs channel stops the remaining workers waiting on receive.

GoResilience

Code

gosnippet
39 lines
package main

import (
	"fmt"
	"sync"
)

func main() {
	jobs := make(chan int)
	var wg sync.WaitGroup

	for worker := 1; worker <= 2; worker++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()
			for {
				job, ok := <-jobs
				if !ok { // 通道关闭:没有更多任务
					return
				}
				if job < 0 { // 约定的哨兵值 (sentinel):提前退出
					fmt.Println("worker", id, "saw sentinel")
					return
				}
				fmt.Println("worker", id, "processed", job)
			}
		}(worker)
	}

	go func() {
		defer close(jobs)
		for _, job := range []int{10, 20, 30, -1} {
			jobs <- job
		}
	}()

	wg.Wait()
	fmt.Println("all workers stopped")
}

Inside the snippet

Structurally, expect the function main and nothing else.

for worker := 1; worker <= 2; worker++ is the loop that carries the per-item work. A goroutine does the work; a channel carries the result back, so the two contexts never share memory directly. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.

Caveats

  • All of it is standard-library — paste it in and it runs.

Putting it to use

Entry signature: func main()

The demo output is labeled (worker, all workers stopped), so the output doubles as a step-by-step trace of what the file did.

Core lines under the microscope

for _, job := range []int{10, 20, 30, -1} {
	jobs <- job
}
jobs := make(chan int)
var wg sync.WaitGroup

Interactive Tools for This Topic

FAQ

What does Sentinel Value Stops Workers print when run?
Execute the whole file; each printed line is prefixed with a label like `worker`, `all workers stopped`.