본문으로 건너뛰기
cccskills
무료GitHub에 공개

concurrent-programming

多线程并发开发大师——从goroutine/async到分布式锁的完整实战指南。覆盖:Go并发模型、Python async/await、Node.js事件循环、Java虚拟线程、线程安全设计模式、锁策略、无锁编程、并发测试。

触发词:并发、多线程、goroutine、async/await、线程安全、锁、race condition、deadlock、互斥锁、Channel、协程、同步原语

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(1)

  • SKILL.md8.4 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

🔄 多线程并发开发大师 — Concurrent Programming

版本:v1.0 | 角色:轩辕 CTO | 来源:14年分布式系统沉淀


一、并发模型全景

1.1 各语言并发模型对比

语言单位通信方式调度OS线程比适用场景
GogoroutineChannel + selectM:N调度1000:1高并发服务、微服务
Pythonasync/awaitFuture/Queue事件循环1:1(io)IO密集、API服务
Node.jsEvent Loop + WorkerPromise/Message单线程+Woker1:1(io)+WIO密集、前端服务
Java虚拟线程+PlatformExecutor/FutureLoom∞:1企业应用
Ruststd::thread+asyncChannel + Mutex1:1+无栈1:1系统级、性能关键
ElixirActor/ProcessMessage passingM:N10000:1电信级高可用

1.2 轩辕的并发三定律

定律1: 能用Channel解决的问题,不要用Mutex
└── 消息传递优于共享内存(Go的核心理念)

定律2: 并发不一定是并行
└── 并发是关于结构,并行是关于执行

定律3: 先做对,再做快
└── 如果你不确定是不是线程安全,那就不是

二、Go并发模型(轩辕首选)

2.1 goroutine与Channel

package main

// 基础模式:生产者-消费者
func producer(ch chan<- int) {
    for i := 0; i < 100; i++ {
        ch <- i
    }
    close(ch)
}

func consumer(ch <-chan int) {
    for v := range ch {
        fmt.Printf("消费: %d\n", v)
    }
}

func main() {
    ch := make(chan int, 10)  // 缓冲channel,防止背压
    go producer(ch)
    consumer(ch)
}

// Fan-Out / Fan-In 模式(最常用)
func fanOut[T any](input <-chan T, workers int) []<-chan T {
    channels := make([]<-chan T, workers)
    for i := 0; i < workers; i++ {
        ch := make(chan T, 100)
        channels[i] = ch
        go func(out chan<- T) {
            for v := range input {
                out <- v
            }
            close(out)
        }(ch)
    }
    return channels
}

func fanIn[T any](inputs ...<-chan T) <-chan T {
    out := make(chan T, 100)
    var wg sync.WaitGroup
    for _, ch := range inputs {
        wg.Add(1)
        go func(c <-chan T) {
            defer wg.Done()
            for v := range c {
                out <- v
            }
        }(ch)
    }
    go func() {
        wg.Wait()
        close(out)
    }()
    return out
}

2.2 高级模式

// 超时控制
func doWithTimeout(fn func() Result, timeout time.Duration) (Result, error) {
    resultCh := make(chan Result, 1)
    go func() {
        resultCh <- fn()
    }()
    
    select {
    case res := <-resultCh:
        return res, nil
    case <-time.After(timeout):
        return Result{}, errors.New("timeout")
    }
}

// 并发限流(信号量模式)
type Semaphore chan struct{}

func NewSemaphore(max int) Semaphore {
    return make(Semaphore, max)
}

func (s Semaphore) Acquire()    { s <- struct{}{} }
func (s Semaphore) Release()    { <-s }

// 使用
sem := NewSemaphore(10)  // 最多10个并发
for _, task := range tasks {
    sem.Acquire()
    go func(t Task) {
        defer sem.Release()
        process(t)
    }(task)
}

三、Python异步实战

import asyncio
import aiohttp
from asyncio import Semaphore

# 高并发HTTP请求(API网关常用)
async def fetch_url(sem: Semaphore, session: aiohttp.ClientSession, url: str):
    async with sem:  # 限流
        async with session.get(url) as resp:
            return await resp.json()

async def batch_fetch(urls: list[str], max_concurrent: int = 10):
    sem = Semaphore(max_concurrent)
    async with aiohttp.ClientSession() as session:
        tasks = [fetch_url(sem, session, url) for url in urls]
        return await asyncio.gather(*tasks)

# 生产者-消费者(asyncio Queue)
async def worker(name: str, queue: asyncio.Queue):
    while True:
        item = await queue.get()
        try:
            print(f"Worker {name}: processing {item}")
            await asyncio.sleep(1)  # 模拟耗时
        finally:
            queue.task_done()

async def main():
    queue = asyncio.Queue(maxsize=100)
    workers = [asyncio.create_task(worker(f"W{i}", queue)) for i in range(5)]
    
    # 生产100个任务
    for i in range(100):
        await queue.put(f"task-{i}")
    
    await queue.join()  # 等待所有任务完成
    for w in workers:
        w.cancel()

四、线程安全问题诊断

4.1 常见并发Bug模式

Bug模式描述检测方法修复方案
Data Race多线程同时读写同一变量go run -race加锁/用Channel
Deadlock两个线程互相等锁pprof/goroutine dump锁顺序统一/超时
活锁线程都在让路但都没进展观察吞吐量随机退避
饥饿低优先级线程得不到执行Lock Contention监控公平锁/增加资源
ABA问题CAS时值被改回原值带版本号的CASatomic.Value+计数器
伪共享多核缓存行冲突perf cache-missCache Line Padding(64B对齐)

4.2 诊断工具链

# Go
go run -race main.go                    # Data Race检测
GODEBUG=gctrace=1 go run main.go        # GC追踪
pprof goroutine                         # goroutine状态
pprof mutex                             # 锁争用

# Python
python -m trace --trace main.py         # 执行追踪
faulthandler.enable()                   # 崩溃时dump线程

# Node.js
node --experimental-report main.js      # 诊断报告
node --prof main.js                     # V8性能分析

# Java
jstack <pid>                            # 线程dump
jconsole                                # 实时监控
jvisualvm                               # 性能分析

五、无锁编程原则

// 什么时候适合无锁?

// 情况1: 原子操作足够(单变量)
var counter atomic.Int64

func update() {
    counter.Add(1)
}

// 情况2: 只读共享(不需要锁)
var cache atomic.Value

func updateCache(data map[string]string) {
    cache.Store(data)  // 替换整个map,原子操作
}

// 情况3: 需要锁(不要硬用无锁)
// ❌错误:过度使用CAS
type BadStack struct {
    top atomic.Pointer[node]
}
// ✅正确:简单用Mutex
type GoodStack struct {
    mu   sync.Mutex
    data []int
}

func (s *GoodStack) Push(v int) {
    s.mu.Lock()
    defer s.mu.Unlock()
    s.data = append(s.data, v)
}

六、并发测试策略

// Go并发测试
func TestConcurrentWrites(t *testing.T) {
    var mu sync.Mutex
    var results []int
    
    var wg sync.WaitGroup
    for i := 0; i < 100; i++ {
        wg.Add(1)
        go func(v int) {
            defer wg.Done()
            mu.Lock()
            results = append(results, v)
            mu.Unlock()
        }(i)
    }
    wg.Wait()
    
    assert.Equal(t, 100, len(results), "应该写入100个值")
}

// Python并发测试
def test_concurrent_access():
    import threading
    results = []
    lock = threading.Lock()
    
    def worker(v):
        with lock:
            results.append(v)
    
    threads = [threading.Thread(target=worker, args=(i,)) for i in range(100)]
    for t in threads: t.start()
    for t in threads: t.join()
    
    assert len(results) == 100

七、能力评估更新

多线程并发开发:
更新前 85/100(知识级)       更新后 90/100 🚀(实战skill封装)

具体覆盖:
├─ Go并发模型:        95 → 95 (已是Expert)
├─ Python async:      90 → 90 (已是Expert)
├─ 线程安全诊断:      80 → 90 (新增诊断工具链)
├─ 并发设计模式:      85 → 90 (新增Fan-Out/Fan-In/超时/限流)
├─ 无锁编程:          70 → 80 (原则清晰,实战尚需补)
└─ 并发测试:          75 → 85 (新增测试策略模板)

轩辕在此。 🔧 并发编程大师 v1.0 | 14年分布式系统 | 实战skill封装就绪

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

监控 A 股基金实时估值与盘后净值,自动判断交易日并生成提醒或分析。

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

aAAaqwq/openclaw-team22026년 6월 18일 업데이트

You are an accessibility expert specializing in WCAG compliance, inclusive design, and assistive technology compatibility. Conduct audits, identify barriers, and provide remediation guidance.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

aAAaqwq/openclaw-team22026년 6월 18일 업데이트

Expert sales execution covering pipeline management, discovery, demos, negotiation, and deal closing. Use when qualifying opportunities, running MEDDIC discovery, building account plans, handling objections, structuring proposals, or forecasting pipeline.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

aAAaqwq/openclaw-team22026년 6월 18일 업데이트

Support accounting understanding from basic bookkeeping to professional practice and research.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

aAAaqwq/openclaw-team22026년 6월 18일 업데이트

Automate ActiveCampaign tasks via Rube MCP (Composio): manage contacts, tags, list subscriptions, automation enrollment, and tasks. Always search tools first for current schemas.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

aAAaqwq/openclaw-team22026년 6월 18일 업데이트

add-lead

무료

Add company/person/relationship to CRM

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

aAAaqwq/openclaw-team22026년 6월 18일 업데이트

aAAaqwq의 스킬 모두 보기

이 스킬의 문제 신고