notque/vexjoy-agent / skills/programming/programming
programming
FlaggedLanguage rules, workflows, and tooling: Go, Python, Rust, Kotlin, Swift, PHP, TypeScript type checks and debugging, OpenStack Python, MCP local-docs servers, Node.js backend APIs.
references/go/concurrency/concurrency-patterns.md
View on GitHub# Go Concurrency Patterns Reference
## Worker Pool Pattern
The standard pattern for processing jobs concurrently with controlled parallelism.
```go
type Job struct {
ID string
Data []byte
}
type Result struct {
JobID string
Value any
Error error
}
func ProcessJobs(ctx context.Context, jobs <-chan Job, numWorkers int) <-chan Result {
results := make(chan Result, numWorkers)
var wg sync.WaitGroup
wg.Add(numWorkers)
for i := 0; i < numWorkers; i++ {
go func(workerID int) {
defer wg.Done()
for {
select {
case job, ok := <-jobs:
if !ok {
return
}
value, err := processJob(ctx, job)
results <- Result{
JobID: job.ID,
Value: value,
Error: err,
}
case <-ctx.Done():
return
}
}
}(i)
}
go func() {
wg.Wait()
close(results)
}()
return results
}
```
## Rate Limiter Pattern
Token-bucket rate limiter with context-aware waiting.
```go
type RateLimiter struct {
rate int
interval time.Duration
tokens chan struct{}
stop chan struct{}
}
func NewRateLimiter(rate int, interval time.Duration) *RateLimiter {
rl := &RateLimiter{
rate: rate,
interval: interval,
tokens: make(chan struct{}, rate),
stop: make(chan struct{}),
}
for i := 0; i < rate; i++ {
rl.tokens <- struct{}{}
}
go rl.refill()
return rl
}
func (rl *RateLimiter) refill() {
ticker := time.NewTicker(rl.interval / time.Duration(rl.rate))
defer ticker.Stop()
for {
select {
case <-ticker.C:
select {
case rl.tokens <- struct{}{}:
default: // Channel full, skip
}
case <-rl.stop:
return
}
}
}
func (rl *RateLimiter) Wait(ctx context.Context) error {
select {
case <-rl.tokens:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (rl *RateLimiter) Stop() {
close(rl.stop)
}
```
## Fan-Out / Fan-In Pattern
```go
// Fan-out: distribute work to multiple goroutines
func fanOut(ctx context.Context, input <-chan Job, workers int) []<-chan Result {
channels := make([]<-chan Result, workers)
for i := 0; i < workers; i++ {
channels[i] = worker(ctx, input)
}
return channels
}
// Fan-in: merge multiple channels into one
func fanIn(ctx context.Context, channels ...<-chan Result) <-chan Result {
out := make(chan Result)
var wg sync.WaitGroup
for _, ch := range channels {
wg.Go(func() { // Go 1.25+; ch is per-iteration since 1.22
for result := range ch {
select {
case out <- result:
case <-ctx.Done():
return
}
}
})
}
go func() {
wg.Wait()
close(out)
}()
return out
}
```
## Pipeline Pattern
```go
func pipeline(ctx context.Context, input <-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for n := range input {
select {
case out <- n * 2:
case <-ctx.Done():
return
}
}
}()
return out
}
```
## Graceful Shutdown Patterns
### Background Worker Lifecycle
```go
type Worker struct {
ctx context.Context
cancel context.CancelFunc
done chan struct{}
}
func NewWorker() *Worker {
ctx, cancel := context.WithCancel(context.Background())
w := &Worker{
ctx: ctx,
cancel: cancel,
done: make(chan struct{}),
}
go w.run()
return w
}
func (w *Worker) run() {
defer close(w.done)
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
w.doWork()
case <-w.ctx.Done():
return
}
}
}
func (w *Worker) Stop() {
w.cancel()
<-w.done // Wait for goroutine to finish
}
```
### Server Graceful Shutdown
```go
func runServer(ctx context.Context) error {
srv := &http.Server{Addr: "127.0.0.1:8080", ReadHeaderTimeout: 5 * time.Second} // loopback by default
errc := make(chan error, 1)
go func() { errc <- srv.ListenAndServe() }()
select {
case err := <-errc:
return fmt.Errorf("serve: %w", err) // startup failure, e.g. port in use
case <-ctx.Done():
}
// WithoutCancel keeps ctx values but not its (already fired) cancellation.
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
return errors.Join(fmt.Errorf("shutdown: %w", err), srv.Close()) // force-close stragglers
}
if err := <-errc; !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
}
```
## Container-Aware GOMAXPROCS (Go 1.25+)
Go 1.25 automatically adjusts GOMAXPROCS based on container CPU limits. No manual configuration needed.
```go
// Before Go 1.25 (no longer needed - can be removed)
import _ "go.uber.org/automaxprocs"
// Go 1.25+: Just works - no code needed!
// Runtime auto-detects: min(host CPUs, cgroup CPU limit)
```
Disabling if needed:
```bash
GODEBUG=containermaxprocs=0 # Disable container detection
GODEBUG=updatemaxprocs=0 # Disable dynamic updates
export GOMAXPROCS=4 # Explicit override
```
Platform support: Linux only (uses cgroups). Does not apply to Windows or macOS.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| rea-changelog-updatemorluto/reaPrepare or rewrite REA release changelogs and GitHub release notes from pinned Git history, with verified contributor thanks and Release Please synchronization. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| academy-guideanthropics/skillsStop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials, and use cases from Claude Academy (academy.claude.com), Anthropic's learning hub. Trigger on: "how do I", "how can I", "getting started with", "what can Claude do", "teach me", "learn to use"; questions about artifacts, projects, skills, plugins, connectors, MCP; requests about rolling Claude out to a team, class, or organization; and any ask for training materials, onboarding content, or learning resources. Use it when the user is learning how to use a feature or product — not when they are mid-task and just want the task done. This skill composes with other skills: after consulting product documentation to answer how a Claude feature works, also check here for a matching course or tutorial — a docs-grounded answer and an Academy recommendation belong together. Only recommend on a strong match; never invent Academy content. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| claude-apianthropics/skillsReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens). SKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file). | Stars: 198k | Updated | Claude CodeCodex | Unverified | Install |
| doc-coauthoringanthropics/skillsGuide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |