goroutine-patterns
Implement Go concurrency patterns using goroutines, channels, and synchronization primitives. Use when building concurrent systems, implementing parallelism, or managing goroutine lifecycles. Trigger words include "goroutine", "channel", "concurrent", "parallel", "sync", "context".
What this skill does
# Goroutine Patterns
Implement Go concurrency patterns for efficient parallel processing.
## Quick Start
**Basic goroutine:**
```go
go func() {
// Runs concurrently
}()
```
**With channel:**
```go
ch := make(chan int)
go func() {
ch <- 42
}()
result := <-ch
```
## Instructions
### Step 1: Choose Concurrency Pattern
**Simple parallel execution:**
```go
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
process(id)
}(i)
}
wg.Wait()
```
**Worker pool:**
```go
jobs := make(chan Job, 100)
results := make(chan Result, 100)
// Start workers
for w := 0; w < numWorkers; w++ {
go worker(jobs, results)
}
// Send jobs
for _, job := range allJobs {
jobs <- job
}
close(jobs)
// Collect results
for range allJobs {
result := <-results
handleResult(result)
}
```
**Pipeline:**
```go
// Stage 1: Generate
gen := func() <-chan int {
out := make(chan int)
go func() {
defer close(out)
for i := 0; i < 10; i++ {
out <- i
}
}()
return out
}
// Stage 2: Process
process := func(in <-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for n := range in {
out <- n * 2
}
}()
return out
}
// Use pipeline
for result := range process(gen()) {
fmt.Println(result)
}
```
### Step 2: Implement Channel Communication
**Unbuffered channel (synchronous):**
```go
ch := make(chan int)
go func() {
ch <- 42 // Blocks until received
}()
value := <-ch // Blocks until sent
```
**Buffered channel (asynchronous):**
```go
ch := make(chan int, 10) // Buffer of 10
ch <- 1 // Doesn't block until buffer full
ch <- 2
value := <-ch // Doesn't block if buffer has data
```
**Select for multiple channels:**
```go
select {
case msg := <-ch1:
fmt.Println("Received from ch1:", msg)
case msg := <-ch2:
fmt.Println("Received from ch2:", msg)
case <-time.After(time.Second):
fmt.Println("Timeout")
}
```
### Step 3: Use Synchronization Primitives
**Mutex for shared state:**
```go
type SafeCounter struct {
mu sync.Mutex
count int
}
func (c *SafeCounter) Inc() {
c.mu.Lock()
defer c.mu.Unlock()
c.count++
}
func (c *SafeCounter) Value() int {
c.mu.Lock()
defer c.mu.Unlock()
return c.count
}
```
**RWMutex for read-heavy workloads:**
```go
type Cache struct {
mu sync.RWMutex
items map[string]string
}
func (c *Cache) Get(key string) (string, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
val, ok := c.items[key]
return val, ok
}
func (c *Cache) Set(key, value string) {
c.mu.Lock()
defer c.mu.Unlock()
c.items[key] = value
}
```
**WaitGroup for goroutine coordination:**
```go
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
doWork(id)
}(i)
}
wg.Wait() // Wait for all goroutines
```
### Step 4: Implement Context for Cancellation
**Basic context usage:**
```go
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
for {
select {
case <-ctx.Done():
return // Exit when cancelled
default:
doWork()
}
}
}()
// Cancel when done
cancel()
```
**With timeout:**
```go
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
result, err := doWorkWithContext(ctx)
if err == context.DeadlineExceeded {
fmt.Println("Operation timed out")
}
```
**Propagate context:**
```go
func ProcessRequest(ctx context.Context, req Request) error {
// Pass context to all operations
data, err := fetchData(ctx, req.ID)
if err != nil {
return err
}
return saveData(ctx, data)
}
```
## Common Patterns
### Fan-Out/Fan-In
```go
func fanOut(in <-chan int, n int) []<-chan int {
outs := make([]<-chan int, n)
for i := 0; i < n; i++ {
outs[i] = process(in)
}
return outs
}
func fanIn(channels ...<-chan int) <-chan int {
out := make(chan int)
var wg sync.WaitGroup
for _, ch := range channels {
wg.Add(1)
go func(c <-chan int) {
defer wg.Done()
for n := range c {
out <- n
}
}(ch)
}
go func() {
wg.Wait()
close(out)
}()
return out
}
```
### Rate Limiting
```go
func rateLimiter(rate time.Duration) <-chan time.Time {
return time.Tick(rate)
}
limiter := rateLimiter(time.Second / 10) // 10 per second
for range limiter {
go processItem()
}
```
### Timeout Pattern
```go
func doWithTimeout(timeout time.Duration) error {
done := make(chan error, 1)
go func() {
done <- doWork()
}()
select {
case err := <-done:
return err
case <-time.After(timeout):
return errors.New("timeout")
}
}
```
### Error Group
```go
import "golang.org/x/sync/errgroup"
func processAll(items []Item) error {
g := new(errgroup.Group)
for _, item := range items {
item := item // Capture for goroutine
g.Go(func() error {
return process(item)
})
}
return g.Wait() // Returns first error
}
```
## Advanced
For detailed patterns:
- [Channels](reference/channels.md) - Channel patterns and best practices
- [Sync](reference/sync.md) - Synchronization primitives
- [Context](reference/context.md) - Context usage and propagation
## Troubleshooting
**Goroutine leaks:**
- Always ensure goroutines can exit
- Use context for cancellation
- Close channels when done
**Deadlocks:**
- Avoid circular channel dependencies
- Don't send on unbuffered channel without receiver
- Use select with timeout
**Race conditions:**
- Use `go run -race` to detect
- Protect shared state with mutexes
- Prefer channels for communication
**Performance issues:**
- Don't create too many goroutines
- Use worker pools for bounded concurrency
- Profile with pprof
## Best Practices
1. **Don't communicate by sharing memory; share memory by communicating**
2. **Always handle goroutine cleanup**: Use context, defer, or done channels
3. **Avoid goroutine leaks**: Ensure all goroutines can exit
4. **Use buffered channels carefully**: Can hide synchronization issues
5. **Prefer sync.WaitGroup**: For waiting on multiple goroutines
6. **Pass context**: Propagate cancellation through call stack
7. **Close channels from sender**: Never close from receiver
8. **Check channel closure**: Use `val, ok := <-ch`
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.