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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.