Basic Rust Thread Example to Perform Concurrent Computation

CK CK 3788 
Created at  
619 0 0

In Rust, you implement a threaded application using the std::thread module. You create new threads using the thread::spawn function, passing a closure or function as an argument that represents the thread's task. This closure receives ownership of any data it needs. Threads communicate through channels (using mpsc or similar) for passing data between them, avoiding data races through proper ownership and borrowing. When the spawned threads finish, you can join them using the join() method to retrieve their results, ensuring that the main thread waits for completion if needed. Error handling is crucial; panics in threads need to be handled gracefully, often by using a Result type within the thread's function.
 

Here’s a simple example of using threads in Rust, demonstrating how to perform concurrent tasks.

use std::thread;
use std::time::Duration;

fn main() {
    let handle1 = thread::spawn(|| {
        for i in 1..5 {
            println!("Thread 1 - Count: {}", i);
            thread::sleep(Duration::from_millis(500)); // Simulate work
        }
    });

    let handle2 = thread::spawn(|| {
        for i in 1..5 {
            println!("Thread 2 - Count: {}", i);
            thread::sleep(Duration::from_millis(400)); // Simulate work
        }
    });

    for i in 1..5 {
        println!("Main Thread - Count: {}", i);
        thread::sleep(Duration::from_millis(300));
    }

    // Wait for the threads to finish
    handle1.join().unwrap();
    handle2.join().unwrap();

    println!("All threads completed.");
}

 

Explanation

  1. Thread Creation:
    • thread::spawn starts a new thread and executes the closure provided.
  2. Simulating Work:
    • thread::sleep(Duration::from_millis(...)) is used to mimic a delay, representing work being done by the threads.
  3. Main Thread:
    • The main thread continues executing alongside the spawned threads.
  4. Thread Synchronization:
    • handle.join() ensures the main thread waits for the spawned threads to complete before exiting.

 

Output Example

The exact order of the output may vary due to concurrent execution:

Main Thread - Count: 1
Thread 1 - Count: 1
Thread 2 - Count: 1
Main Thread - Count: 2
Thread 1 - Count: 2
Thread 2 - Count: 2
Main Thread - Count: 3
Thread 1 - Count: 3
Thread 2 - Count: 3
Main Thread - Count: 4
Thread 1 - Count: 4
Thread 2 - Count: 4
All threads completed.

This example demonstrates Rust's ability to handle threads safely and efficiently. Each thread runs independently, and the main thread ensures they complete before the program exits using the join method.

Tags Rust Thread mpsc spawn thread Facebook X
Comments 0
Similar posts
  1. The || syntax in Rust - also known as a closure
    602
  2. Multi-threaded HLS Server in Rust
    774
  3. Rust Std misc
    375
  4. Rust Std library types
    370
  5. Rust Thread Example
    346
  6. How do I get the maximum available of thread in python?
    995
  7. Method to maximize full CPU performance with Python
    325
  8. Thread Application Implementation in TThread
    670
  9. Calling Your Main Thread From A Worker Thread In C#
    551
  1. How do I implement a heap in Rust?
    685
  2. How do I implement a stack in Rust?
    771
  3. Rust-GPU-tools for interacting with various GPU APIs
    757
  4. Rust array is fixed size. Can I modify its content?
    587
  5. Rust Example for Array and Dyamic Element Management (aka Vector-based Element Management)
    624
  6. Run a specific module in a external file with Rust
    571
  7. Question(?) Operator in Rust
    573
  8. Rust code example to access MySQL
    1,100
  9. Rust Documentation
    316
  10. Rust Compatibility
    726
  11. Rust Unsafe Operations
    369
  12. Rust Testing
    1,246
  13. Rust Error Handling
    350
  14. Rust Macro Rules
    1,525
  15. Rust mechanism for defining shared behavior across different types - Traits
    1,774
  16. Rust Scoping Rules - only accessible within the block of code
    1,075
  17. Rust Generics - Generalizing types and functionalities
    1,358
  18. Rust Attributes for conditional compilation, crate, lints, mark functions, macros
    318
  19. Rust Package Management Tool - cargo
    307
  20. Rust compilation unit - Crates
    254
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  4. How do I create animated background for Google Meet?
    23,256
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    105
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  8. Array of arguments passed to script in PHP
    99
  9. Invalid Auction Storms in Ad Tech
    108
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    209
  11. The Two Clocks of Ad Server Architecture
    78
  12. Frequency Cap Architecture Overview
    527
  13. Collecting Proof-of-Play from 100,000 Screens
    154
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    303
  15. What is RedisVL?
    117
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  17. TPU & GPU Cluster Management Tools
    258
  18. The Concept of Scaffolding in AI Agents
    245
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    599
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    269
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    355
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  23. Machine Learning: Training vs. Ranking
    231
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    229
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    204
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    264
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233