Token导航 LogoToken导航TokenDH.com
开发执行命令github未标认证来源可访问许可证需确认审计通过

rust-concurrencyRust concurrency 搜索

Agent Skill

rust-concurrency 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

282

周安装

12

GitHub Stars

29

下载量

99
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:rust-concurrency(Rust concurrency 搜索)
来源仓库:https://github.com/huiali/rust-skills
仓库路径:skills/rust-concurrency
安装命令:
npx skills add https://github.com/huiali/rust-skills --skill rust-concurrency
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/huiali/rust-skills --skill rust-concurrency

简介

rust-concurrency 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息。

  • 适合在 Codex、Claude、Cursor、Gemini CLI 中搜索 Rust 并发编程相关资料时使用。
  • 支持查找线程安全、异步处理与并行模式的最佳实践。
  • 安装前建议确认权限范围、维护状态及是否会触发外部查询或缓存更新。
  • 可结合来源仓库和原始 README 继续核验具体搜索策略与返回格式。

SKILL.md

Concurrency vs Async

DimensionConcurrency (threads)Async (async/await)
MemoryEach thread has separate stackSingle thread reused
BlockingBlocks OS threadDoesn't block, yields
Use caseCPU-intensiveI/O-intensive
ComplexitySimple and directRequires runtime

Key Insight: Threads for parallelism, async for concurrency.

Send/Sync Quick Reference

Send - Can Transfer Ownership Between Threads

Basic types → automatically Send
Contains references → automatically Send
Raw pointers → NOT Send
Rc → NOT Send (non-atomic ref counting)

Rule: If all fields are Send, the type is Send.

Sync - Can Share References Between Threads

&T where T: Sync → automatically Sync
RefCell → NOT Sync (runtime checking not thread-safe)
MutexGuard → NOT Sync (intentionally)

Rule: &T is Send if T is Sync.

Solution Patterns

Pattern 1: Shared Mutable State

use std::sync::{Arc, Mutex};

let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];

for _ in 0..10 {
    let counter = Arc::clone(&counter);
    let handle = std::thread::spawn(move || {
        let mut num = counter.lock().unwrap();
        *num += 1;
    });
    handles.push(handle);
}

for handle in handles {
    handle.join().unwrap();
}

When to use: Multiple threads need to mutate shared data.

Trade-offs: Lock contention can limit scalability.

Pattern 2: Message Passing

use std::sync::mpsc;

let (tx, rx) = mpsc::channel();

thread::spawn(move || {
    tx.send("hello").unwrap();
});

println!("{}", rx.recv().unwrap());

When to use: Threads communicate without shared state.

Trade-offs: Copy/move overhead for messages.

Pattern 3: Async Runtime (Tokio)

use tokio;

#[tokio::main]
async fn main() {
    let handle = tokio::spawn(async {
        // Async task
        fetch_data().await
    });

    let result = handle.await.unwrap();
}

When to use: I/O-bound operations (network, filesystem).

Trade-offs: Requires async runtime, function coloring.

Workflow

Step 1: Choose Concurrency Model

CPU-intensive task?
  → Use threads (rayon for data parallelism)

I/O-intensive task?
  → Use async/await (tokio, async-std)

Both?
  → Use async with spawn_blocking for CPU work

Step 2: Determine Data Sharing Strategy

No shared state?
  → Message passing (mpsc channels)

Read-heavy shared state?
  → Arc<RwLock<T>>

Write-heavy shared state?
  → Arc<Mutex<T>> or lock-free alternatives

Simple counters/flags?
  → Atomic types (AtomicUsize, AtomicBool)

Step 3: Verify Thread Safety

Check Send bounds
  → Can transfer ownership?

Check Sync bounds
  → Can share references?

Test for data races
  → Use miri, loom, or thread sanitizers

Common Errors & Solutions

ErrorCauseSolution
E0277 Send not satisfiedContains non-Send typesCheck all fields, replace Rc with Arc
E0277 Sync not satisfiedShared reference type not SyncWrap with Mutex/RwLock
DeadlockInconsistent lock orderingEstablish and follow lock hierarchy
MutexGuard across awaitLock held while suspendedScope lock before await point
Data race (runtime)Improper synchronizationUse proper sync primitives

Deadlock Prevention

Rule 1: Consistent Lock Ordering

// Always lock A before B
let _lock_a = resource_a.lock();
let _lock_b = resource_b.lock();
// Never lock B before A elsewhere

Rule 2: Minimize Lock Scope

// ❌ Bad: lock held too long
let guard = data.lock();
do_work(&guard);
more_work();  // still locked

// ✅ Good: release early
{
    let guard = data.lock();
    do_work(&guard);
}  // lock released
more_work();

Rule 3: Avoid Locks Across Await

// ❌ Bad: lock across await
let guard = mutex.lock().unwrap();
async_call().await;  // DEADLOCK RISK

// ✅ Good: drop lock before await
let value = {
    let guard = mutex.lock().unwrap();
    guard.clone()
};  // lock dropped
async_call().await;

Performance Considerations

StrategyWhen to UseTrade-offs
Fine-grained lockingLock small portionsMore complex, avoid contention
RwLockRead-heavy workloadsSlower writes than Mutex
AtomicsSimple counters/flagsLimited operations, no compound ops
Message passingAvoid shared stateCopy/move overhead
Lock-free structuresHigh contentionComplex, use crates (crossbeam)

Async-Specific Patterns

Spawning Tasks

// Spawn independent task
tokio::spawn(async move {
    process_data(data).await
});

// Spawn with 'static requirement
tokio::spawn(async move {
    let data = Arc::clone(&data);  // Share ownership
    work_with(data).await
});

Concurrent Operations

use tokio::join;

// Wait for all to complete
let (result1, result2, result3) = tokio::join!(
    fetch_user(),
    fetch_posts(),
    fetch_comments()
);

// First to complete
let result = tokio::select! {
    r = fetch_from_primary() => r,
    r = fetch_from_backup() => r,
};

Timeout and Cancellation

use tokio::time::{timeout, Duration};

match timeout(Duration::from_secs(5), long_operation()).await {
    Ok(result) => result,
    Err(_) => {
        // Operation timed out
    }
}

Review Checklist

When reviewing concurrent code:

  • All shared data properly synchronized (Arc/Mutex/RwLock)
  • Send/Sync bounds satisfied for types crossing threads
  • No locks held across await points
  • Consistent lock ordering to prevent deadlocks
  • Appropriate choice between threads and async
  • Message passing channels used correctly (no deadlocks)
  • Atomic operations used for simple shared state
  • Thread pool sized appropriately for workload
  • Error handling for lock poisoning
  • Graceful shutdown and resource cleanup

Verification Commands

# Check compilation with thread safety
cargo check

# Run tests with thread sanitizer (requires nightly)
RUSTFLAGS="-Z sanitizer=thread" cargo +nightly test

# Test with miri (detect undefined behavior)
cargo +nightly miri test

# Use loom for exhaustive concurrency testing
cargo test --features loom

# Check for race conditions
cargo clippy -- -W clippy::mutex_atomic

Common Pitfalls

1. Rc in Multi-threaded Context

Symptom: E0277 error, Rc cannot be sent between threads

Fix: Replace Rc with Arc

// ❌ Bad
let data = Rc::new(value);
thread::spawn(move || { /* use data */ });

// ✅ Good
let data = Arc::new(value);
thread::spawn(move || { /* use data */ });

2. Lock Across Await Points

Symptom: Deadlock or "future cannot be sent between threads safely"

Fix: Drop lock before await

// ❌ Bad
let guard = mutex.lock().unwrap();
async_fn().await;

// ✅ Good
let value = mutex.lock().unwrap().clone();
drop(guard);  // Explicit drop
async_fn().await;

3. Missing Arc Clone

Symptom: Borrow checker errors when spawning threads

Fix: Clone Arc before moving into closure

// ❌ Bad
let data = Arc::new(vec![1, 2, 3]);
thread::spawn(move || { /* data moved */ });
// data is gone

// ✅ Good
let data = Arc::new(vec![1, 2, 3]);
let data_clone = Arc::clone(&data);
thread::spawn(move || { /* data_clone moved */ });
// data still available

Related Skills

  • rust-async - Advanced async patterns (Stream, select, backpressure)
  • rust-async-pattern - Async architecture and design patterns
  • rust-ownership - Understanding ownership for thread safety
  • rust-mutability - Interior mutability patterns (Cell, RefCell)
  • rust-performance - Concurrency performance optimization
  • rust-unsafe - Writing safe concurrent abstractions

Localized Reference

  • Chinese version: SKILL_ZH.md - 完整中文版本,包含所有内容

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

38.63%
按下载量换算38

Claude

32.54%
按下载量换算32

Cursor

17.65%
按下载量换算17

Gemini CLI

8.56%
按下载量换算8

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

执行命令

安装流程涉及命令执行,可能通过 npx skills add https://github.com/huiali/rust-skills --skill rust-concurrency 联网下载 Skill 或依赖。用户安装前应确认命令来源、仓库内容和执行环境。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills