kmaruthi2002/universal-llm-skills/concurrency-and-async
Claude Code and agent skill by kmaruthi2002/universal-llm-skills
- community
Checking that the SKILL.md file is still in the repository.
Write and debug correct concurrent and asynchronous code: choosing between threads, processes, async/await and event loops, actors, and worker pools; avoiding data races, race conditions, deadlocks, livelocks and starvation; managing shared state with locks, atomics, immutability or message passing; structured concurrency, cancellation and timeouts; backpressure and bounded queues; and testing concurrent code. Use when code runs in parallel or asynchronously, when adding async/await, threads, goroutines, workers or background jobs, when results are nondeterministic, something hangs or deadlocks, an event loop is blocked, or throughput under load is poor. For distributed-system consistency use system-design; for job scheduling use scheduled-jobs.
Install
npx vskill@latest install kmaruthi2002/universal-llm-skills/concurrency-and-asyncSKILL.md
The same SKILL.md was published earlier as kmaruthi2002/universal-llm-skills/concurrency-and-async.
Concurrency and Async
Concurrency is about structuring a program as multiple tasks whose execution can overlap; parallelism is about actually running them at the same time. Async is a way of expressing concurrency in which tasks voluntarily yield while waiting. All three trade simplicity for throughput or responsiveness, and all three introduce a class of bugs — races, deadlocks, lost updates, leaks of unfinished work — that are rare, timing-dependent, and hard to reproduce. The craft is choosing the simplest model that meets the need and confining shared mutable state so the hard bugs cannot occur.
Scope
Covers: in-process concurrency models, synchronisation, shared state, cancellation, backpressure, async runtimes, and how to test and debug concurrent code, across languages.
Neighbours:
- Consistency across machines, distributed locks, consensus, replication →
system-design. - Database transaction isolation and locking →
database-design,sql-and-queries. - Making work faster in general →
performance-optimization. - Retries, timeouts, and failure semantics →
error-handling. - Cron-like and queued background work →
scheduled-jobs.
Core principles
- Shared mutable state is the root of most concurrency bugs. A race requires two tasks touching the same data, at least one writing, without coordination. Remove any one of those three conditions — don't share, don't mutate, or coordinate — and the bug class disappears. Prefer the first two; coordination is the hardest to get right.
- Choose the model by the bottleneck. I/O-bound work (waiting on network, disk, databases) benefits from concurrency — async or many threads — because tasks mostly wait. CPU-bound work benefits only from parallelism across cores — threads (in runtimes that allow true parallel execution), processes, or native code. Async does nothing for CPU-bound work and can make it worse by blocking the event loop.
- Every task needs an owner and a lifetime. A task started without anyone waiting for it, cancelling it, or collecting its errors is a leak: its failures vanish and it may outlive the request that started it. Structured concurrency — tasks scoped to a block that waits for all of them — makes lifetimes explicit.
- Bound everything. Unbounded queues, unbounded task spawning, and unbounded pools turn overload into memory exhaustion or latency collapse. Bounds create backpressure, which is how a system says "slow down" instead of falling over.
- Correctness can't be established by testing alone. Interleavings are combinatorially many; a test passing 1,000 times proves little. Reason about invariants, use designs that make races impossible, and use tools (race detectors, model checkers, deterministic schedulers) that explore interleavings systematically.
- Simpler beats faster. Fine-grained locking, lock-free structures, and clever memory-ordering tricks are expert territory. Use them only when profiling shows coarse synchronisation is the bottleneck — and prefer battle-tested library implementations to your own.
Concurrency models
| Model | How it works | Good for | Watch out for | |
|---|---|---|---|---|
| OS threads + shared memory | Preemptively scheduled threads share an address space | CPU parallelism (where runtime permits); blocking libraries | Races, deadlocks; ~MBs of stack per thread; thousands of threads get expensive | |
| Thread / worker pools | Fixed set of threads consuming tasks from a queue | Bounded parallelism; reuse | Pool starvation when tasks block waiting on other tasks in the same pool | |
| Processes | Separate address spaces; communicate via IPC | CPU parallelism in runtimes with a global interpreter lock; isolation of crashes | Startup cost; serialisation overhead; memory duplication | |
| Async / await on an event loop | Cooperative tasks yield at await; one (or few) threads run many tasks | Very high numbers of concurrent I/O-bound operations | Any blocking call stalls everything; "function colouring" (async spreads through call chains) | |
| Green threads / goroutines / virtual threads | Runtime-scheduled lightweight threads; blocking-style code | Massive I/O concurrency with simple sequential code | Still shared memory — races remain; pinning or blocking native calls can starve the scheduler | |
| Actors | Isolated state per actor; communicate only by asynchronous messages | Stateful concurrent entities; fault isolation and supervision | Mailbox growth (needs backpressure); request–response via messages adds complexity; ordering assumptions | |
| CSP / channels | Tasks communicate over channels; "share memory by communicating" | Pipelines, fan-out/fan-in, worker coordination | Deadlocks from unbuffered channels with no reader; goroutine leaks on abandoned channels | |
| Data parallelism | Same operation over partitions of data (parallel map, SIMD, GPU) | Numeric and bulk data processing | Partitioning overhead; reduction correctness |
Examples by ecosystem (not mandates): Python — asyncio/trio/anyio, threading (I/O-bound), multiprocessing/concurrent.futures (CPU-bound); JavaScript — the event loop, Promises, worker_threads/Web Workers for CPU; Go — goroutines, channels, sync, context; Java/Kotlin — executors, virtual threads, CompletableFuture, coroutines; C# — async/await, Task, TPL; Rust — threads with Send/Sync, tokio/async-std, rayon for data parallelism; Erlang/Elixir — processes and supervision trees.
Choosing
- Mostly waiting on I/O, many concurrent operations → async or lightweight threads, whichever the codebase uses.
- CPU-heavy work that can be split → a pool sized to core count (threads or processes depending on runtime); keep it off the event loop.
- A few independent background activities → plain threads or tasks with clear ownership.
- Many stateful entities processing events (sessions, devices, game objects) → actors or one task per entity with a mailbox.
- Streaming pipelines → channels/queues with bounded buffers between stages.
- Simple scripts → sequential code; add concurrency only when measurements show waiting dominates.
Mixing models (e.g. calling blocking code from async, or async from threads) is common and is where many bugs arise. Use the runtime's bridges deliberately: run blocking work in a thread pool from async (run_in_executor, spawn_blocking, Task.Run), and run async code from sync contexts through a single entry point rather than nested event loops.
Hazards and how to recognise them
Data race: unsynchronised concurrent access to the same memory with at least one write. In some languages (C, C++, Go, Rust-unsafe) this is undefined or unspecified behaviour; in managed languages it produces torn reads, lost updates, or stale values. Detect with race detectors (e.g. Go -race, ThreadSanitizer for C/C++/Rust, Java tools) running your tests.
Race condition (higher-level): correctness depends on timing even when each access is individually synchronised. The classic is check-then-act:
and read-modify-write:
Fixes: make the compound operation atomic (a lock around both steps, an atomic primitive like compare-and-swap or fetch_add, a database constraint or conditional update such as UPDATE ... SET balance = balance - 10 WHERE balance >= 10, an upsert, or optimistic concurrency with version numbers). Note that in async code, races occur across await points: state read before an await may have changed after it, even on a single thread.
Deadlock: tasks each hold a resource and wait for another's. Requires (Coffman conditions) mutual exclusion, hold-and-wait, no preemption, and circular wait. Prevent by breaking one:
- Global lock ordering: always acquire locks in a consistent order (e.g. by account ID).
- Don't hold a lock while calling unknown code (callbacks, virtual methods, I/O, other services).
- Acquire with timeouts (try-lock) and back off.
- Use one coarser lock instead of several fine ones.
- Async variants: awaiting a task that awaits you; a bounded channel where the producer waits for space while the consumer waits for the producer; synchronously blocking on an async result inside the event loop (
.Result,block_onin an async context).
Livelock: tasks keep responding to each other without progress (both back off and retry in lockstep). Fix with randomised backoff.
Starvation: a task never gets the resource — unfair locks, priority inversions, a reader-preferring lock with constant readers, a pool full of tasks waiting on tasks queued behind them.
Blocked event loop: a synchronous CPU-heavy or blocking call (file I/O, sleep, a sync HTTP client, a heavy JSON parse, a tight loop) inside async code stalls every other task. Symptoms: latency spikes across unrelated requests, timeouts, health checks failing. Many runtimes offer slow-callback or blocked-loop detection in debug mode.
Lost or leaked tasks: fire-and-forget tasks whose exceptions are never observed, that keep running after their parent returned, or whose results are discarded. Often visible as "Task exception was never retrieved" warnings, growing goroutine counts, or memory growth.
Memory visibility and ordering: without synchronisation, one thread may not see another's writes, or may see them in a different order. Locks, atomics, volatile/acquire-release semantics, and channels establish "happens-before" relations. Double-checked locking without proper memory ordering is a classic bug. When in doubt, use higher-level primitives that handle this for you.
Managing shared state
In order of preference:
- Don't share. Give each task its own data; partition work so tasks touch disjoint data; combine results at the end (map-reduce).
- Share only immutable data. Immutable values can be read concurrently with no synchronisation. Copy-on-write and persistent data structures make "modification" produce new versions.
- Transfer ownership via messages. Send data through a channel or to an actor; the sender stops using it. Only one task owns it at a time. Rust's ownership system enforces this; elsewhere it's a discipline.
- Confine state to one task. One task owns the state; others ask it to act via messages (the actor pattern, or a single "owner" goroutine/task).
- Use concurrent data structures and atomics from the standard library for simple shared counters, maps, and queues — but remember a concurrent map makes individual operations safe, not compound check-then-act sequences.
- Use locks. Keep critical sections small, never do I/O or call unknown code inside them, always release (use scoped constructs:
with lock:,defer mu.Unlock(), RAII guards,lockstatements), and document which lock guards which data. Readers–writer locks help only when reads dominate and critical sections are non-trivial; measure.
Locks vs message passing. Message passing scales better in reasoning: each piece of state has one owner, and interactions are explicit. Locks are simpler for small, local shared structures and have less overhead. A common good design: message passing between components, small locks inside a component.
Database as the shared state. Many "concurrency" bugs in web services are races on database rows across requests or instances. In-process locks don't help across instances. Use transactions with the right isolation level, row locks (SELECT ... FOR UPDATE), conditional updates, unique constraints, or optimistic concurrency (version columns). See database-design.
Structured concurrency and cancellation
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 90 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/concurrency-and-async/SKILL.md
Popularity
- 7-day trend score
- 0
Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/kmaruthi2002/universal-llm-skills/concurrency-and-async)