tokio
БесплатноБез исполняемых скриптовНе проверенTokio is the asynchronous runtime for Rust: a task scheduler, async TCP/UDP, timers, channels and synchronization primitives that most async Rust crates…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
Tokio — Async Runtime for Rust
Overview
Tokio runs async Rust code. #[tokio::main] starts a multi-threaded scheduler, tokio::spawn runs futures as lightweight tasks, and the net, time, sync, io, fs, process and signal modules provide async versions of the std building blocks. The current release is 1.54.1 (2026-10-21, MSRV 1.85). Tokio keeps a rolling MSRV of at least six months and designates some minor versions as LTS (1.51.x until March 2027, 1.53.x until September 2027); pin to an LTS line, for example version = "~1.53", if you cannot raise your Rust version often.
Instructions
Install
# Cargo.toml
[dependencies]
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util", "time", "sync", "signal"] }
tokio-util = { version = "0.7", features = ["rt"] } # CancellationToken; the "rt" feature adds TaskTracker
features = ["full"] turns everything on and is fine for applications; libraries should enable only what they use. Without macros and rt-multi-thread, #[tokio::main] does not compile.
Tasks, join, select, blocking work
use tokio::time::{sleep, timeout, Duration};
fn checksum_all(files: Vec<String>) -> u64 {
files.iter().map(|f| f.len() as u64).sum() // stands in for CPU-heavy work
}
#[tokio::main]
async fn main() {
let a = tokio::spawn(async {
sleep(Duration::from_secs(1)).await;
"invoice sync done"
});
let b = tokio::spawn(async {
sleep(Duration::from_millis(500)).await;
"cache warm done"
});
// join! waits for both; each JoinHandle yields Result<T, JoinError>
let (ra, rb) = tokio::join!(a, b);
println!("{}, {}", ra.unwrap(), rb.unwrap());
// select! runs both branches until one finishes, then drops the other
tokio::select! {
_ = sleep(Duration::from_secs(1)) => println!("slow path"),
_ = sleep(Duration::from_millis(100)) => println!("fast path"),
}
// timeout wraps any future; Err(Elapsed) if it does not finish in time
match timeout(Duration::from_millis(200), sleep(Duration::from_secs(5))).await {
Ok(_) => println!("finished"),
Err(_) => println!("timed out after 200ms"),
}
// CPU-heavy or blocking std code goes to the blocking pool
let total = tokio::task::spawn_blocking(|| checksum_all(vec!["a.log".into(), "b.log".into()]))
.await
.unwrap();
println!("{total}");
}
Futures are lazy: nothing runs until awaited or spawned. A spawned task must be Send + 'static, so move owned data into it (async move).
Channels
use tokio::sync::{broadcast, mpsc, oneshot, watch};
#[tokio::main]
async fn main() {
// mpsc: many producers, one consumer; bounded, so send().await applies backpressure
let (tx, mut rx) = mpsc::channel::<String>(100);
for id in 0..3 {
let tx = tx.clone();
tokio::spawn(async move { tx.send(format!("worker {id} ready")).await.unwrap(); });
}
drop(tx); // recv() returns None only after every sender is dropped
while let Some(msg) = rx.recv().await {
println!("{msg}");
}
// oneshot: one value, one reply (request/response)
let (reply_tx, reply_rx) = oneshot::channel::<u32>();
tokio::spawn(async move { let _ = reply_tx.send(42); });
println!("answer {}", reply_rx.await.unwrap());
// broadcast: every receiver sees every message; slow receivers get RecvError::Lagged
let (btx, mut brx1) = broadcast::channel::<String>(16);
let mut brx2 = btx.subscribe();
btx.send("deploy started".into()).unwrap();
println!("{} / {}", brx1.recv().await.unwrap(), brx2.recv().await.unwrap());
// watch: latest value only, for config or state that changes
let (wtx, mut wrx) = watch::channel(String::from("v1"));
wtx.send("v2".into()).unwrap();
wrx.changed().await.unwrap();
println!("config now {}", *wrx.borrow());
}
TCP echo server with graceful shutdown
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
#[tokio::main]
async fn main() -> std::io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:8080").await?;
let token = CancellationToken::new();
let tracker = TaskTracker::new();
let shutdown = token.clone();
tokio::spawn(async move {
tokio::signal::ctrl_c().await.expect("failed to listen for ctrl-c");
shutdown.cancel();
});
loop {
tokio::select! {
_ = token.cancelled() => break,
accepted = listener.accept() => {
let (mut socket, addr) = accepted?;
println!("connection from {addr}");
let conn_token = token.clone();
tracker.spawn(async move {
let mut buf = [0u8; 1024];
loop {
tokio::select! {
_
Установить tokio в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл tokio?
Tokio is the asynchronous runtime for Rust: a task scheduler, async TCP/UDP, timers, channels and synchronization primitives that most async Rust crates (axum, hyper, reqwest, tonic) run on. Use it when asked to write async Rust, spawn concurrent tasks, build a TCP server, use mpsc or broadcast channels, add timeouts, limit concurrency with a semaphore, run blocking code from async code, or shut a Tokio service down gracefully.
Как установить скилл tokio?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл tokio запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic