Logo van Go Concurrency Foundations

Go Concurrency Foundations

Community
v0lka
go-concurrency-foundations

Guides the agent to avoid foundational concurrency mistakes in Go: confusing concurrency with parallelism, assuming concurrency is always faster, misusing channels vs mutexes, ignoring data races and race conditions, mis-sizing worker pools for CPU- vs I/O-bound work, and misunderstanding Go contexts. Use when writing, reviewing, or refactoring any concurrent Go code, goroutines, channels, mutexes, worker pools, or context usage.

Overzicht

Uitgeverv0lka
Repositoryskills
Skillnaamgo-concurrency-foundations
Sterren
28
Forks
1
Meegeleverde bestanden
Alleen instructies
LicentieMIT
Links
  • Instructies in Markdown

    Het model laadt het bestand SKILL.md alleen als dat nodig is. Dat kost dus alleen tokens als een verzoek daadwerkelijk bij de skill past.

  • Werkt met elk LLM

    AI-skills bestaan uit instructies in gewone Markdown, niet uit aanbiederspecifieke code. Daardoor werken ze met GPT, Claude, Gemini, Grok of een lokaal model.

  • Compleet zonder extra bestanden

    Alles wat het model nodig heeft, staat in de instructies — geen extra bestanden om te synchroniseren.

  • Open source

    Gepubliceerd door v0lka op GitHub. Bekijk de bronbestanden voordat je de skill installeert.

Installatie

Installeer de AI-skill Go Concurrency Foundations in TypingMind om deze met elk LLM te gebruiken, of voeg de skill toe aan een andere agent die SKILL.md kan lezen.

1

Installeren in TypingMind

TypingMind installeert een skill rechtstreeks vanuit de GitHub-map. De app leest SKILL.md, bundelt de bijbehorende bestanden en slaat het resultaat lokaal op.

  1. Open de app en ga naar Plug-ins → Skills.
  2. Kies "Installeren via GitHub".
  3. Plak de onderstaande URL van de skillmap en bevestig.
    https://github.com/v0lka/skills/tree/main/development/idiomatic-go/go-concurrency-foundations
  4. Schakel de skill in voor elke chat waarin je de skill wilt kunnen gebruiken.
Plug-ins → Skills → Skill toevoegen → Via GitHub-URL. Plak vervolgens de map-URL en druk op Doorgaan.
2

Installeren in een andere agent

Elke agent die het Agent Skills-formaat kan lezen, kan deze skill gebruiken — kopieer de map naar de skillmap van die agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/v0lka/skills.git /tmp/skills
mkdir -p .claude/skills
cp -r /tmp/skills/development/idiomatic-go/go-concurrency-foundations .claude/skills/go-concurrency-foundations
Start Claude Code na het kopiëren opnieuw op, zodat de nieuwe skill wordt herkend.

Gebruik deze skill in TypingMind

Schakel Go Concurrency Foundations in voor een chat naar keuze in TypingMind en het model doet de rest. De naam en beschrijving staan in de systeemprompt. Zodra een verzoek bij de skill past, laadt het model zelf de volledige instructies. Je hoeft de skill nooit handmatig aan te roepen. Pas als het model de skill daadwerkelijk gebruikt, kost dat tokens.

Het model laadt Go Concurrency Foundations automatisch zodra een verzoek erbij past.

Werkt met elk AI-model

AI-skills zijn gewone Markdown-instructies in plaats van aanbiederspecifieke code. Daardoor is Go Concurrency Foundations niet gebonden aan het model waarvoor de skill is geschreven. Installeer de skill één keer in TypingMind en gebruik deze met GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama of een lokaal model dat je zelf draait — allemaal met je eigen API-sleutels.

  • Alleen geladen wanneer nodig

    De systeemprompt bevat alleen de naam en beschrijving. De instructies worden bij het eerste bijpassende verzoek opgehaald, dus een ongebruikte skill kost niets.

  • Wissel van model tijdens een chat

    Omdat de skill uit instructies bestaat en niet uit code, blijft deze werken als je van model wisselt — het volgende model leest hetzelfde SKILL.md-bestand.

Skillinstructies

Dit is de inhoud van SKILL.md die het model laadt. Lees deze vóór de installatie — een skill bestaat uit instructies die je model zal volgen.

Go Concurrency Foundations

Rules derived from "100 Go Mistakes" #55-#60. Apply whenever writing or reviewing concurrent Go code.


1. Concurrency vs Parallelism (#55)

  • Concurrency is about structure -- decomposing a problem into independently executing steps that coordinate.
  • Parallelism is about execution -- running the same step on multiple cores simultaneously.
  • Concurrency enables parallelism but is not the same thing.
  • When restructuring code, ask: "Am I changing the structure (concurrency) or adding more workers to the same step (parallelism)?"

2. Concurrency Is Not Always Faster (#56)

Go scheduling essentials

  • Goroutines are multiplexed onto OS threads (M) by the Go runtime, not the OS.
  • GOMAXPROCS limits the number of OS threads executing user-level Go code simultaneously (defaults to logical CPU count since Go 1.5).
  • The scheduler uses per-P local queues, a global queue, and work stealing.
  • Since Go 1.14 the scheduler is preemptive (10 ms time slice).

Key rule: small workloads kill parallelism

Spinning up a goroutine per tiny unit of work makes things slower -- the goroutine creation and scheduling overhead dominates. Always use a threshold to fall back to sequential execution for small inputs.

go
const threshold = 2048 // tune via benchmarks on target hardware

func parallelMergesort(s []int) {
    if len(s) <= 1 {
        return
    }
    if len(s) <= threshold {
        sequentialMergesort(s) // fall back to sequential
        return
    }

    middle := len(s) / 2
    var wg sync.WaitGroup
    wg.Add(2)
    go func() {
        defer wg.Done()
        parallelMergesort(s[:middle])
    }()
    go func() {
        defer wg.Done()
        parallelMergesort(s[middle:])
    }()
    wg.Wait()
    merge(s, middle)
}

Checklist before adding concurrency

  1. Start with a correct sequential version.
  2. Profile and benchmark to confirm the bottleneck.
  3. Introduce concurrency with a tunable threshold or pool size.
  4. Benchmark the concurrent version -- if it is not measurably faster, keep the sequential one.

3. Channels vs Mutexes (#57)

Use this decision guide:

SituationPrefer
Parallel goroutines accessing/mutating a shared resourcesync.Mutex (or sync/atomic)
Concurrent goroutines that need to coordinate, signal, or transfer ownershipChannels
Signaling completion or readiness (with or without data)Channels (chan struct{} for no data)
Protecting a critical section (read/write to shared state)sync.Mutex / sync.RWMutex
Transferring ownership of a resource from one stage to the nextChannels
  • Do NOT force channels everywhere just because Go says "share memory by communicating." Mutexes and channels are complementary.
  • If goroutines are parallel (same step, multiple workers): think mutexes.
  • If goroutines are concurrent (different steps in a pipeline): think channels.

4. Data Races vs Race Conditions (#58)

Definitions

  • Data race: two+ goroutines access the same memory location concurrently and at least one writes. Detected by go test -race / go run -race.
  • Race condition: behavior depends on uncontrolled timing of events. A data-race-free program can still have race conditions.

Eliminating data races does NOT guarantee deterministic results.

Preventing data races

Choose one of:

  1. Atomic operations -- sync/atomic for simple numeric types.
  2. Mutex -- sync.Mutex / sync.RWMutex to guard a critical section.
  3. Channel communication -- ensure only one goroutine writes to the variable.
go
// BAD -- data race
i := 0
go func() { i++ }()
go func() { i++ }()

// GOOD -- atomic
var i int64
go func() { atomic.AddInt64(&i, 1) }()
go func() { atomic.AddInt64(&i, 1) }()

// GOOD -- mutex
var mu sync.Mutex
i := 0
go func() { mu.Lock(); i++; mu.Unlock() }()
go func() { mu.Lock(); i++; mu.Unlock() }()

// GOOD -- channel (only parent writes)
ch := make(chan int)
go func() { ch <- 1 }()
go func() { ch <- 1 }()
i := <-ch + <-ch

Race condition (data-race-free but non-deterministic)

go
// No data race, but i is unpredictably 1 or 2
var mu sync.Mutex
i := 0
go func() { mu.Lock(); i = 1; mu.Unlock() }()
go func() { mu.Lock(); i = 2; mu.Unlock() }()

To enforce ordering, use channels for coordination, not just mutexes.

Go memory model guarantees

Memorize these ordering rules:

  1. Goroutine creation happens-before the goroutine starts executing.
  2. Goroutine exit is NOT guaranteed to happen before any event -- always synchronize if the parent reads state written by the child.
  3. Channel send happens-before the corresponding receive completes.
  4. Channel close happens-before a receive observing the closure.
  5. Unbuffered channel receive happens-before the send completes.
    • This means with an unbuffered channel, a write before the receive is guaranteed visible after the send returns.
    • This guarantee does NOT hold for buffered channels.
go
// SAFE -- unbuffered channel guarantees ordering
i := 0
ch := make(chan struct{})
go func() {
    i = 1
    <-ch
}()
ch <- struct{}{}
fmt.Println(i) // guaranteed to print 1

// UNSAFE -- buffered channel, data race on i
ch := make(chan struct{}, 1)
go func() {
    i = 1
    <-ch
}()
ch <- struct{}{}
fmt.Println(i) // data race

5. Worker Pool Sizing by Workload Type (#59)

WorkloadPool size guideline
CPU-boundruntime.GOMAXPROCS(0) (number of OS threads, defaults to logical CPUs)
I/O-boundDepends on the external system's capacity; tune via load testing
  • Use runtime.GOMAXPROCS(0) (read-only call) to get the current value.
  • Do NOT use runtime.NumCPU() for pool sizing -- GOMAXPROCS may be set lower than the CPU count (e.g., in containers).
  • For CPU-bound work, more goroutines than GOMAXPROCS causes unnecessary context switching with no throughput gain.

Worker pool template

go
func process(r io.Reader) (int, error) {
    var count int64
    n := runtime.GOMAXPROCS(0) // CPU-bound: match available threads

    ch := make(chan []byte, n)
    var wg sync.WaitGroup
    wg.Add(n)
    for i := 0; i < n; i++ {
        go func() {
            defer wg.Done()
            for b := range ch {
                v := task(b)
                atomic.AddInt64(&count, int64(v))
            }
        }()
    }

    for {
        b := make([]byte, 1024)
        _, err := r.Read(b)
        if err != nil {
            if err == io.EOF {
                break
            }
            close(ch)
            return 0, err
        }
        ch <- b
    }
    close(ch)
    wg.Wait()
    return int(count), nil
}

6. Go Contexts (#60)

When to create which context

ConstructorUse case
context.WithTimeout(parent, d)Cancel after a duration (e.g., RPC deadline)
context.WithDeadline(parent, t)Cancel at an absolute time
context.WithCancel(parent)Manual cancellation signal (e.g., graceful shutdown)
context.WithValue(parent, k, v)Carry request-scoped metadata (trace IDs, auth)
context.Background()Top-level / main / test entry point
context.TODO()Placeholder when the correct context is not yet available

Mandatory rules

  1. Always defer cancel() after WithTimeout, WithDeadline, or WithCancel. Forgetting leaks the internal timer goroutine until the timeout fires.

    go
    ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
    defer cancel() // always, even if the function returns early
  2. Use unexported key types for context values to prevent cross-package collisions.

    go
    type ctxKey string
    const traceIDKey ctxKey = "traceID"
    
    ctx = context.WithValue(ctx, traceIDKey, "abc-123")
  3. Never block on channel send/receive in a context-aware function without selecting on ctx.Done().

    go
    // BAD -- blocks even if context is canceled
    ch <- msg
    v := <-ch
    
    // GOOD -- respects context cancellation
    select {
    case <-ctx.Done():
        return ctx.Err()
    case ch <- msg:
    }
    
    select {
    case <-ctx.Done():
        return ctx.Err()
    case v := <-ch:
        // use v
    }
  4. Check ctx.Err() to distinguish cancellation causes:

    • context.Canceled -- explicit cancel.
    • context.DeadlineExceeded -- timeout or deadline passed.
  5. Functions that users wait for should accept a context.Context as the first parameter so upstream callers can control cancellation.

  6. Prefer context.TODO() over context.Background() when the right context is unclear or not yet propagated -- it signals intent to revisit.

Veelgestelde vragen

Wat doet de AI-skill Go Concurrency Foundations?

Guides the agent to avoid foundational concurrency mistakes in Go: confusing concurrency with parallelism, assuming concurrency is always faster, misusing channels vs mutexes, ignoring data races and race conditions, mis-sizing worker pools for CPU- vs I/O-bound work, and misunderstanding Go contexts. Use when writing, reviewing, or refactoring any concurrent Go code, goroutines, channels, mutexes, worker pools, or context usage.

Waarom Go Concurrency Foundations gebruiken in TypingMind?

Omdat je deze skill één keer installeert en met elk model kunt gebruiken. Go Concurrency Foundations bestaat uit gewone Markdown in plaats van aanbiederspecifieke code. Dezelfde skill werkt dus met GPT-5, Claude, Gemini, Grok of een lokaal model. Ook als je midden in een chat van model wisselt, blijft de skill werken. TypingMind werkt met je eigen API-sleutels, dus je betaalt aanbieders rechtstreeks in plaats van een abonnement per gebruikersplek af te sluiten. Je skills en chats blijven in je eigen opslag.

Hoe installeer ik Go Concurrency Foundations in TypingMind?

Open Plug-ins → Skills → Installeren vanaf GitHub in TypingMind en plak https://github.com/v0lka/skills/tree/main/development/idiomatic-go/go-concurrency-foundations. TypingMind leest het bestand SKILL.md en installeert het als een skill die je per chat kunt inschakelen.

Welke AI-modellen kunnen Go Concurrency Foundations gebruiken?

Elk model dat je in TypingMind koppelt. AI-skills bestaan uit gewone Markdown-instructies in plaats van aanbiederspecifieke code. GPT, Claude, Gemini, Grok en lokale modellen kunnen deze skill dus allemaal laden wanneer een verzoek erbij past.

Hoeveel AI-modellen kan ik met Go Concurrency Foundations gebruiken?

Zoveel als je wilt. Je kunt Go Concurrency Foundations gebruiken met elk model dat skills ondersteunt, zoals GPT, Claude, Gemini, Grok, DeepSeek, Mistral of Llama. Allemaal in TypingMind met je eigen API-sleutels.

Is de AI-skill Go Concurrency Foundations gratis?

Ja. Deze skill is door v0lka op GitHub gepubliceerd onder de licentie MIT. Je betaalt alleen je eigen AI-aanbieder voor de tokens die je gebruikt.

Wat zijn AI-skills?

Een AI-skill is een herbruikbare bundel instructies die een AI-model leert hoe het één specifieke taak moet uitvoeren. De skill volgt het open Agent Skills-formaat: het bestand SKILL.md bevat de naam en beschrijving van de skill. Daarnaast kan de skill scripts, sjablonen of referentiebestanden bevatten die het model nodig heeft. Het model leest de instructies alleen als je verzoek bij de skill past. Een geïnstalleerde skill kost dus niets zolang deze niet wordt gebruikt.

Waarin verschillen AI-skills van plug-ins of MCP-servers?

Een plug-in of MCP-server geeft een model nieuwe tools om aan te roepen: code die ergens wordt uitgevoerd en een resultaat teruggeeft. Een AI-skill geeft het model juist kennis en een werkwijze: hoe het een taak moet aanpakken, welke stappen het moet volgen en hoe goede uitvoer eruitziet. Skills bestaan uit gewone Markdown en hebben dus geen server, API-sleutel of runtime nodig. Ze werken met elk model.

Bekijk alles

Maak nu je eigen AI-werkruimte

Schrijf je in voor onze nieuwsbrief en blijf op de hoogte van nieuwe functies en toekomstige weggeefacties 👇