Rust มีความสามารถในการจัดการ concurrent programming ที่ปลอดภัยและทรงพลัง บทความนี้จะพาคุณไปรู้จักกับแนวทางการเขียน concurrent code ใน Rust ด้วย thread, async/await และ tokio ซึ่งเป็น runtime ที่ได้รับความนิยมสูง
การใช้ Thread ใน Rust
Rust รองรับการสร้าง thread ได้โดยตรงผ่าน std::thread ซึ่งมี API ที่ง่ายและปลอดภัยแบบ ownership-based
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
for i in 1..5 {
println!("thread: {}", i);
thread::sleep(Duration::from_millis(100));
}
});
for i in 1..5 {
println!("main: {}", i);
thread::sleep(Duration::from_millis(100));
}
handle.join().unwrap();
}
โดยค่า ownership ของตัวแปรใน closure จะต้องส่งเข้าไปอย่างเหมาะสม เช่นใช้ move
การใช้ async/await ใน Rust
ตั้งแต่ Rust 1.39 เป็นต้นมา เราสามารถใช้ async/await เพื่อเขียนโค้ดแบบ asynchronous ได้ง่ายมากขึ้น
async fn say_hello() {
println!("Hello from async!");
}
#[tokio::main]
async fn main() {
say_hello().await;
}

async fn จะคืนค่าเป็น Future ซึ่งสามารถ await ได้ใน context ที่เป็น async เท่านั้น
ทำความรู้จักกับ tokio
tokio คือ asynchronous runtime ที่มี scheduler ประสิทธิภาพสูง มีทั้ง multi-thread และ single-thread runtime
ติดตั้ง
# Cargo.toml
[dependencies]
tokio = { version = “1”, features = [“full”] }
ใช้งาน async task
use tokio::time::{sleep, Duration};
#[tokio::main]
async fn main() {
let task = tokio::spawn(async {
sleep(Duration::from_secs(1)).await;
println!("async task done!");
});
task.await.unwrap();
}

การสื่อสารระหว่าง task/thread ด้วย channel
Rust มี channel สำหรับการส่งข้อมูลระหว่าง threads และ tasks ทั้งแบบ sync และ async
use tokio::sync::mpsc;
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel(32);
tokio::spawn(async move {
tx.send("hello").await.unwrap();
});
while let Some(msg) = rx.recv().await {
println!("Received: {}", msg);
}
}
Thread vs Async vs Tokio
| คุณสมบัติ | Thread | Async/Await | Tokio |
|---|---|---|---|
| การรันพร้อมกัน | แท้จริง (OS thread) | จำลอง (Future) | จัดการโดย runtime |
| ประสิทธิภาพ | ใช้ CPU/Memory สูง | ประหยัดทรัพยากร | ดีเยี่ยม |
| เหมาะกับ | งาน CPU-bound | งาน I/O-bound | งาน I/O-bound หลาย task |
บทสรุป
Rust ให้เครื่องมือสำหรับการทำ concurrent programming ที่หลากหลาย ตั้งแต่ thread แบบพื้นฐาน ไปจนถึง async/await และ runtime อย่าง tokio ที่สามารถจัดการ task นับพัน ๆ ได้อย่างมีประสิทธิภาพ การเลือกใช้ให้เหมาะสมกับลักษณะงานจะช่วยเพิ่ม performance และความปลอดภัยให้กับโปรเจกต์ของคุณ
บทความโดย poolsawat.com – Rust Programming สำหรับระบบที่เร็ว ปลอดภัย และทันสมัย