Skip to main content

Command Palette

Search for a command to run...

Rust-এ Concurrency: Threads, Channels, Arc, Mutex & Async

Published
2 min read
M

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 মূলত চারটি অংশে ভাগ করা যায়:

  1. Threads

  2. Channels

  3. Shared state: Arc & Mutex

  4. 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 consumer

  • tx.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 ownership

  • Mutex<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 করতে পারে safely

  • Mutex → ensures one thread at a time updates counter

  • Compiler 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 thread

  • Multiple async tasks same thread এ efficiently run করে

Real-life use case:

  • Web servers, network I/O, async database queries, chat servers

More from this blog

DSA মানে শুধু LeetCode না — DSA মানে Production System slow না করা

অনেকেই বলে — “ভাই, Web Development-এ DSA লাগে না” আসলে Junior Developer থাকলে এমনটাই মনে হয়।আমি নিজেও Junior থাকতে তাই ভাবতাম। আমার আবার একটা বাজে স্বভাব আছে 😅👉 কোন কিছুর বাস্তব প্রয়োজন না বুঝলে সেটা আমার মাথায় ঢুকে না। Junior থাকতে DSA শিখেছি...

Dec 24, 20253 min read
DSA মানে শুধু LeetCode না — DSA মানে Production System slow না করা

🦀 Rust-এ মেমরি ম্যানেজমেন্ট: GC ছাড়া In-depth.

Rust-এ Garbage Collector (GC) নেই, কিন্তু মেমরি নিরাপত্তা (memory safety) আর performance Rust-এর সবচেয়ে শক্তিশালী দিক।তাই, Go-এর মতো runtime-based GC না থাকা সত্ত্বেও Rust compile-time এ মেমরি ম্যানেজ করে Ownership System, Borrow Checker, আর Lifetime...

Oct 5, 202523 min read
🦀 Rust-এ মেমরি ম্যানেজমেন্ট: GC ছাড়া In-depth.

Morshedul Munna

45 posts

As a Software Developer, I am like an architect who designs and builds digital Products. I use my knowledge and expertise to create modern applications that are both efficient and elegant.