Rust-এ Concurrency: Threads, Channels, Arc, Mutex & Async
A self-motivated and enthusiastic web developer with a deep interest in JavaScript (React.js). To work in the Software industry with modern web technologies of different local & multinational Software/ IT agencies of Bangladesh and grow rapidly with increasing responsibilities.
Rust concurrency safe এবং efficient। Rust compile-time-এ check করে data race বা memory issues না হয়। Concurrency মূলত চারটি অংশে ভাগ করা যায়:
Threads
Channels
Shared state: Arc & Mutex
Async programming (Tokio runtime)
১️⃣ Threads with std::thread
Thread হলো independent execution path। Rust standard library std::thread দিয়ে thread তৈরি করা যায়।
Example:
use std::thread;
fn main() {
let handle = thread::spawn(|| {
for i in 1..5 {
println!("Hi from thread! {}", i);
}
});
for i in 1..5 {
println!("Hi from main thread! {}", i);
}
handle.join().unwrap(); // Wait for thread to finish
}
ব্যাখ্যা:
thread::spawn→ নতুন thread start করে।handle.join()→ main thread অপেক্ষা করে spawned thread শেষ হওয়া পর্যন্ত।Memory safe, compiler ensures no dangling reference।
Real-life use case:
- Background tasks, computation-heavy jobs, concurrent downloads।
২️⃣ Channels for communication
Threads একসাথে communicate করতে channels ব্যবহার করা হয়।
Example:
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
tx.send("Hello from thread!").unwrap();
});
let message = rx.recv().unwrap();
println!("{}", message);
}
ব্যাখ্যা:
mpsc::channel→ multiple producers, single consumertx.send→ message পাঠায়rx.recv→ message receive করে
Real-life use case:
- Worker thread pool, logging system, event handling।
৩️⃣ Shared State: Arc & Mutex
যদি multiple threads same data access করে, Rust forbids data races। আমরা use করি:
Arc<T>→ atomic reference-counted pointer, shared ownershipMutex<T>→ mutual exclusion, ensures only one thread can access at a time
Example:
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..5 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}
ব্যাখ্যা:
Arc→ multiple threads same memory access করতে পারে safelyMutex→ ensures one thread at a time updates counterCompiler ensures no data race
Real-life use case:
- Shared counters, caches, database connection pools।
৪️⃣ Async Programming with Tokio runtime
Rust async programming non-blocking I/O এবং lightweight concurrency জন্য।
Example:
use tokio::time::{sleep, Duration};
#[tokio::main]
async fn main() {
let task1 = tokio::spawn(async {
sleep(Duration::from_secs(2)).await;
println!("Task 1 done");
});
let task2 = tokio::spawn(async {
sleep(Duration::from_secs(1)).await;
println!("Task 2 done");
});
task1.await.unwrap();
task2.await.unwrap();
}
ব্যাখ্যা:
tokio::spawn→ lightweight async task.await→ wait without blocking threadMultiple async tasks same thread এ efficiently run করে
Real-life use case:
- Web servers, network I/O, async database queries, chat servers




