Rust Thread Example

CK CK 3788 
Created at
Updated at  
345 0 0

For concurrent applications in Rust, Tokio is a highly recommended runtime. It provides an event-driven, non-blocking I/O model built on top of the asynchronous programming features in the language, making it efficient and suitable for handling many concurrent tasks without the overhead of threads. While other runtimes exist, Tokio's maturity, community support, and comprehensive features make it a strong choice for most projects.

Below is an example of a simple Rust application that demonstrates using threads. The program spawns multiple threads to perform concurrent calculations and waits for all threads to complete.


Example: Multithreaded Sum Calculation

use std::thread;

fn main() {
    // Data to be processed
    let data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    // Split data into chunks
    let chunk_size = 2;
    let chunks: Vec<_> = data.chunks(chunk_size).collect();

    // Create a vector to hold thread handles
    let mut handles = Vec::new();

    // Spawn threads
    for chunk in chunks {
        let chunk = chunk.to_vec(); // Clone the chunk for the thread
        let handle = thread::spawn(move || {
            let sum: i32 = chunk.iter().sum();
            println!("Chunk: {:?}, Sum: {}", chunk, sum);
            sum // Return the sum
        });
        handles.push(handle);
    }

    // Collect results from threads
    let mut total_sum = 0;
    for handle in handles {
        match handle.join() {
            Ok(sum) => total_sum += sum,
            Err(_) => println!("A thread panicked!"),
        }
    }

    println!("Total sum: {}", total_sum);
}

Explanation:

  1. Splitting Data:
    • The data is split into smaller chunks, each processed by a separate thread.
  2. Spawning Threads:
    • thread::spawn is used to create new threads, each receiving its chunk of data.
  3. Joining Threads:
    • The join method waits for threads to complete and collects their results.
  4. Handling Panics:
    • If a thread panics, it’s caught, and an error message is printed.
  5. Output: Each thread prints its chunk and partial sum, and the main thread aggregates the total sum.

Output:

Chunk: [1, 2], Sum: 3
Chunk: [3, 4], Sum: 7
Chunk: [5, 6], Sum: 11
Chunk: [7, 8], Sum: 15
Chunk: [9, 10], Sum: 19
Total sum: 55

This example illustrates how threads can be used for parallel computation in Rust. Let me know if you'd like to see more advanced threading examples, such as using channels for inter-thread communication!
 

Tags Multi-Thread Rust Rust Thread Thread Thread Application Facebook X
Comments 0
Similar posts
  1. How do I setup Rust development environment?
    366
  2. Rust - System Programming Language invented by Graydon Hoare
    277
  3. Rust Code Testing Environment without installing anything on your computer
    321
  4. Arrays and Slices in Rust
    333
  5. Rust Std library types
    367
  6. Rust Std misc
    367
  7. Basic Rust Thread Example to Perform Concurrent Computation
    611
  8. The || syntax in Rust - also known as a closure
    599
  9. How do I get the maximum available of thread in python?
    981
  10. Method to maximize full CPU performance with Python
    314
  11. Multi-threaded Web Server based in Node.js
    860
  12. Trackback module used for Python Threading debugging
    840
  13. Why America's Biggest Tech Companies Are Betting on Rust?
    284
  14. Thread Application Implementation in TThread
    662
  15. Calling Your Main Thread From A Worker Thread In C#
    544
  1. Rust compilation unit - Crates
    249
  2. Rust Modules - Visivility, Struct Visibility, Use Declaration, super and self, File Hierarchy
    1,881
  3. Rust functions - Methods, Closures, Capturing
    1,191
  4. Rust Flow of Control - if/else, loop. while, for and range, match, if let, let-else, while let
    332
  5. Rust Expressions
    918
  6. Rust Conversion - From, Into, TryFrom, TryInto
    1,296
  7. gRPC library for Rust
    335
  8. Rust Data Type Operations - Casting, Literals, Inference, Aliasing
    325
  9. Variable Bindings in Rust
    958
  10. Rust Custom Data Types - struct, enum, use, constants
    296
  11. Arrays and Slices in Rust
    333
  12. Tuples in Rust - a collection of values of different types
    296
  13. Literals and operators in Rust
    293
  14. Rust Data Type - What is mutable?
    256
  15. Rust Code Testing Environment without installing anything on your computer
    321
  16. How do I setup Rust development environment?
    366
  17. Rust - System Programming Language invented by Graydon Hoare
    277
  18. Why America's Biggest Tech Companies Are Betting on Rust?
    284
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,728
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    85
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    198
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    509
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    233
  17. The Concept of Scaffolding in AI Agents
    222
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    576
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    253
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    328
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252