Logo Backend Concurrency Mechanics

Backend Concurrency Mechanics

Cộng đồng
j4flmao
backend-concurrency-mechanics

Use this skill when the user says 'race condition', 'data race', 'goroutine vs thread', 'event loop blocking', 'memory barrier', 'memory model', 'mutex vs atomic', 'deadlock', 'thread pool sizing', 'virtual threads', 'async vs threads'. Explains how OS threads, M:N schedulers (Go goroutines, Java virtual threads), and event loops (Node.js, Python asyncio) actually execute work, and gives correct synchronization patterns for backend services. Do NOT use for: cross-process locks (backend-distributed-locking), job queues (backend-background-jobs), database isolation levels (backend-database-patterns).

Tổng quan

Nhà phát hànhj4flmao
Kho mãagent-skills
Tên kỹ năngbackend-concurrency-mechanics
Sao
41
Bản fork
6
Tệp đi kèm
Chỉ có hướng dẫn
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI dùng hướng dẫn viết bằng Markdown thay vì mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Hướng dẫn có đủ mọi thứ cần thiết

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được j4flmao công bố trên GitHub. Hãy đọc các tệp nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Backend Concurrency Mechanics trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL của thư mục kỹ năng được hiển thị bên dưới rồi xác nhận.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/concurrency
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/backend/universal/concurrency .claude/skills/backend-concurrency-mechanics
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Backend Concurrency Mechanics trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự nạp Backend Concurrency Mechanics ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên bạn có thể dùng Backend Concurrency Mechanics với cả những mô hình khác ngoài mô hình ban đầu. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên khi kỹ năng chưa được dùng, bạn không tốn token cho phần hướng dẫn.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Concurrency Mechanics

Purpose

Pick the right concurrency model for a workload and write shared-state code that is correct under the language's memory model. Most production concurrency bugs come from unsynchronized shared state, blocking an event loop, or unbounded parallelism; this skill targets those.

Agent Protocol

Trigger

Exact user phrases: "race condition", "data race", "goroutine vs thread", "event loop blocking", "memory barrier", "memory model", "mutex vs atomic", "deadlock", "thread pool sizing", "virtual threads", "async vs threads".

Input Context

  • Language/runtime and version (Go, Java 21+, Node.js, Python, Rust, .NET).
  • Workload type: I/O-bound, CPU-bound, or mixed.
  • The shared state or code path that misbehaves; any race detector output.

Output Artifact

Explanation of the execution model plus corrected code. No files unless requested.

Response Format

Model: {OS threads | M:N (goroutines/virtual threads) | event loop}
Workload: {I/O-bound | CPU-bound}
Shared state: {what} -> {mutex | atomic | channel/actor | immutable copy}
Bound: {pool size / semaphore N}
Verify: {go test -race | jcstress | stress test}

Execution Models

ModelExamplesSchedulingCost per unitBlocking call behaviour
1:1 OS threadsJava platform threads, C++ std::thread, Python threadsKernel schedulerEach thread reserves a stack (commonly 1 MB on Windows, 8 MB virtual on Linux glibc, committed lazily) plus kernel structuresBlocks only that thread
M:N user-spaceGo goroutines, Java 21 virtual threads, Erlang processesRuntime multiplexes many tasks onto a few OS threadsSmall growable stacks (Go starts at 2 KB)Runtime parks the task; blocking syscalls may pin a carrier thread
Event loopNode.js (libuv), Python asyncio, Netty, Redis command executionSingle thread runs callbacks/coroutines when I/O is ready (epoll, kqueue, IOCP)Very cheap per connectionAny CPU-heavy or synchronous call stalls every request

Go scheduler (G-M-P)

  • G goroutine, M OS thread, P logical processor holding a local run queue; GOMAXPROCS sets the number of Ps (defaults to CPU count; since Go 1.25 it also respects cgroup CPU limits on Linux).
  • An idle P steals half of another P's local queue (work stealing) and also polls the global queue and network poller.
  • When a goroutine enters a blocking syscall, its M is detached from the P so another M can keep running goroutines.

Java virtual threads (Java 21+)

  • Mounted on a small ForkJoinPool of carrier threads; blocking I/O unmounts them.
  • Pinning: in Java 21-23, blocking inside synchronized pins the carrier; JDK 24 (JEP 491) removed that for synchronized. Native calls still pin.
  • Do not pool virtual threads; limit concurrency to downstream resources with a Semaphore.

Node.js event loop

  • JavaScript runs on one thread; network I/O is non-blocking via the OS; file system, DNS lookup, crypto and zlib use the libuv thread pool (default 4, UV_THREADPOOL_SIZE).
  • Microtasks (resolved promises, queueMicrotask) drain fully after each macrotask, so a promise loop can starve I/O.
  • CPU-bound work goes to worker_threads or another service.

Memory Models in Practice

Compilers and CPUs reorder memory operations. x86 (TSO) only allows a later load to pass an earlier store; ARM and POWER allow much more reordering. You do not write fences by hand in application code: the language memory model guarantees visibility when you use its synchronization primitives.

LanguageHappens-before established by
Gochannel send/receive, sync.Mutex, sync.WaitGroup, sync/atomic (sequentially consistent)
Javasynchronized, volatile, java.util.concurrent locks/atomics, Thread.start/join
C++/Ruststd::atomic with acquire/release or seq_cst ordering, mutexes
JSSingle-threaded; SharedArrayBuffer + Atomics between workers

A data race is two concurrent accesses to the same memory, at least one a write, without happens-before ordering. In Go and C++ the result is undefined behaviour territory (torn reads, stale values); do not reason about "benign" races.

Correct Patterns (Go)

go
package counter

import (
	"context"
	"sync"
	"sync/atomic"

	"golang.org/x/sync/errgroup"
)

// Single integer: atomic is enough.
type Hits struct{ n atomic.Int64 }

func (h *Hits) Inc()         { h.n.Add(1) }
func (h *Hits) Load() int64  { return h.n.Load() }

// Compound invariant (map + total) needs a mutex: atomics cannot make
// two updates appear as one.
type Stats struct {
	mu     sync.Mutex
	byPath map[string]int
	total  int
}

func NewStats() *Stats { return &Stats{byPath: make(map[string]int)} }

func (s *Stats) Record(path string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.byPath[path]++
	s.total++
}

// Bounded fan-out: never start one goroutine per item without a limit.
func FetchAll(ctx context.Context, urls []string, fetch func(context.Context, string) error) error {
	g, ctx := errgroup.WithContext(ctx)
	g.SetLimit(16) // bound concurrency to protect downstreams
	for _, u := range urls {
		g.Go(func() error { return fetch(ctx, u) }) // Go 1.22+: loop var is per-iteration
	}
	return g.Wait() // first error cancels ctx for the rest
}

Verify with go test -race ./... in CI; the race detector only finds races on executed paths, so run it with concurrent tests.

Choosing a Primitive

SituationUse
Single counter/flagAtomic
Several fields that must change togetherMutex (RWMutex only if reads dominate and critical sections are long enough to matter)
Ownership transfer / pipeline stagesChannels or queues
Read-mostly configImmutable snapshot swapped via atomic pointer (atomic.Pointer[T], AtomicReference)
Limit concurrent calls to a dependencySemaphore / bounded pool
Per-key serializationShard locks by hash of key, or an actor/queue per key

Pool Sizing

  • CPU-bound: about the number of cores; more threads only add context switches.
  • I/O-bound with threads: Little's law, concurrency = throughput x latency (e.g. 200 req/s x 0.05 s = 10 in flight), then cap at what the downstream (DB pool, API rate limit) accepts.
  • The DB connection pool is usually the real limit; size app concurrency to it, not the other way round.

Deadlocks and Liveness

  • Acquire multiple locks in one global order.
  • Never hold a lock while doing I/O or calling unknown callbacks.
  • Always pass deadlines (context.Context, CompletableFuture.orTimeout, AbortSignal.timeout).
  • Goroutine leaks: every goroutine needs an exit path (closed channel or cancelled context); monitor runtime.NumGoroutine().

Anti-Patterns

Anti-patternFix
sync.WaitGroup + shared slice append without lockPre-size slice and write by index, or collect via channel
JSON.parse of 50 MB or bcrypt sync calls in Node request pathStream/parse in worker thread; use async APIs
time.Sleep/polling for coordinationChannels, condition variables, or context
Check-then-act on shared map (if !exists { insert })Single critical section or LoadOrStore
Unbounded goroutines/threads per requesterrgroup limit, semaphore, worker pool

Checklist

  • Execution model and workload type identified.
  • Every shared mutable value has one documented synchronization mechanism.
  • Concurrency bounded per downstream dependency.
  • Event loop free of CPU-heavy or synchronous calls.
  • Race detector / stress tests in CI; goroutine or thread counts monitored.

References

  • Related skills: skills/backend/universal/distributed-locking/SKILL.md, skills/backend/universal/background-jobs/SKILL.md, skills/backend/universal/resilience-patterns/SKILL.md.

Câu hỏi thường gặp

Kỹ năng AI Backend Concurrency Mechanics làm được gì?

Use this skill when the user says 'race condition', 'data race', 'goroutine vs thread', 'event loop blocking', 'memory barrier', 'memory model', 'mutex vs atomic', 'deadlock', 'thread pool sizing', 'virtual threads', 'async vs threads'. Explains how OS threads, M:N schedulers (Go goroutines, Java virtual threads), and event loops (Node.js, Python asyncio) actually execute work, and gives correct synchronization patterns for backend services. Do NOT use for: cross-process locks (backend-distributed-locking), job queues (backend-background-jobs), database isolation levels (backend-database-pa...

Vì sao nên dùng Backend Concurrency Mechanics trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Backend Concurrency Mechanics là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Backend Concurrency Mechanics trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/concurrency. TypingMind đọc tệp SKILL.md rồi cài đặt kỹ năng để bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Backend Concurrency Mechanics?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Có thể dùng Backend Concurrency Mechanics với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Backend Concurrency Mechanics với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Backend Concurrency Mechanics có miễn phí không?

Có. Kỹ năng này được j4flmao phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp các công cụ mới mà mô hình có thể gọi. Khi mô hình gọi một công cụ, mã của công cụ đó chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và những tiêu chí mà kết quả cần đáp ứng. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇