Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

1 Commit
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Rust Async & Concurrency Programming Examples

๐Ÿฆ€ A comprehensive collection of Rust asynchronous and concurrent programming examples, demonstrating various patterns, primitives, and best practices.

๐Ÿ“‹ Table of Contents

โœจ Features

๐Ÿงต Thread Operations

  • Basic thread creation and management
  • Thread-safe data sharing with Arc and Mutex
  • Data parallelism with Rayon
  • Scoped threads
  • Work-stealing scheduling

๐Ÿ”’ Synchronization Primitives

  • Mutex - Mutual exclusion
  • RwLock - Reader-writer locks
  • Condvar - Condition variables
  • Barrier - Thread synchronization barriers
  • OnceCell - One-time initialization
  • parking_lot - High-performance locking primitives

โšก Async Programming

  • async/await fundamentals
  • Future and Stream abstractions
  • Async task management
  • Timeout handling
  • Stream processing with buffering
  • Task selection with select!
  • Async synchronization primitives

๐Ÿ“จ Message Passing

  • Standard library mpsc channels
  • Multi-producer, single-consumer patterns
  • crossbeam channels
  • flume high-performance channels
  • Work queue patterns

โš›๏ธ Atomic Operations

  • Atomic counters
  • Atomic booleans
  • Compare-and-swap operations
  • Memory ordering
  • Lock-free data structures

๐Ÿงฎ Concurrent Algorithms

  • Concurrent merge sort
  • Async merge sort
  • Concurrent quicksort
  • Parallel search
  • Producer-consumer patterns
  • Map-Reduce patterns

๐Ÿš€ Quick Start

Prerequisites

  • Rust 1.70+ (with async/await support)
  • Cargo package manager

Installation

# Clone the repository
git clone https://github.com/chord233/rust-async-concurrency.git
cd rust-async-concurrency

# Build the project
cargo build

# Run all examples
cargo run all

Running Specific Examples

# Thread operations
cargo run threads

# Synchronization primitives
cargo run sync

# Async programming
cargo run async

# Message passing
cargo run channels

# Atomic operations
cargo run atomic

# Concurrent algorithms
cargo run algorithms

# Performance benchmarks
cargo run benchmarks

๐Ÿ“š Examples

Thread Operations

// Basic thread creation
let handle = std::thread::spawn(|| {
    println!("Hello from thread!");
});
handle.join().unwrap();

// Shared data with Arc<Mutex<T>>
let counter = Arc::new(Mutex::new(0));
let handles: Vec<_> = (0..10).map(|_| {
    let counter = Arc::clone(&counter);
    std::thread::spawn(move || {
        let mut num = counter.lock().unwrap();
        *num += 1;
    })
}).collect();

Async Programming

// Basic async function
async fn fetch_data() -> String {
    tokio::time::sleep(Duration::from_millis(100)).await;
    "Data fetched".to_string()
}

// Concurrent async tasks
let tasks: Vec<_> = (0..10).map(|i| {
    tokio::spawn(async move {
        fetch_data().await
    })
}).collect();

let results = futures::future::join_all(tasks).await;

Message Passing

// MPSC channel
let (tx, rx) = std::sync::mpsc::channel();

std::thread::spawn(move || {
    tx.send("Hello").unwrap();
});

let message = rx.recv().unwrap();
println!("Received: {}", message);

Atomic Operations

use std::sync::atomic::{AtomicUsize, Ordering};

let counter = AtomicUsize::new(0);
counter.fetch_add(1, Ordering::SeqCst);
let value = counter.load(Ordering::SeqCst);

๐Ÿ“ฆ Dependencies

  • tokio - Async runtime
  • futures - Async abstractions
  • async-std - Alternative async runtime
  • rayon - Data parallelism
  • crossbeam - Concurrent programming tools
  • flume - High-performance channels
  • parking_lot - High-performance locking
  • once_cell - One-time initialization
  • dashmap - Concurrent hash map
  • arc-swap - Atomic Arc swapping

๐Ÿƒ Performance Benchmarks

Run performance comparisons between different approaches:

cargo run benchmarks

Benchmarks include:

  • Thread vs Async task performance
  • Different lock implementations
  • Channel performance comparison
  • Atomic vs Mutex performance

๐Ÿ“– Learning Resources

Books

Documentation

Articles

๐Ÿงช Testing

# Run all tests
cargo test

# Run tests with output
cargo test -- --nocapture

# Run specific module tests
cargo test threads
cargo test async_programming

๐Ÿ”ง Development

Code Structure

src/
โ”œโ”€โ”€ main.rs              # Entry point and CLI
โ”œโ”€โ”€ threads.rs           # Thread operations
โ”œโ”€โ”€ sync_primitives.rs   # Synchronization primitives
โ”œโ”€โ”€ async_programming.rs # Async programming examples
โ”œโ”€โ”€ channels.rs          # Message passing
โ”œโ”€โ”€ atomic_operations.rs # Atomic operations
โ”œโ”€โ”€ concurrent_algorithms.rs # Concurrent algorithms
โ””โ”€โ”€ examples.rs          # Example runner and benchmarks

Adding New Examples

  1. Add your example function to the appropriate module
  2. Update the run_examples() function in that module
  3. Add tests for your example
  4. Update the README if needed

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

Guidelines

  • Follow Rust naming conventions
  • Add comprehensive documentation
  • Include tests for new examples
  • Ensure code is formatted with cargo fmt
  • Run cargo clippy to check for common mistakes

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • The Rust community for excellent documentation and tools
  • Tokio team for the amazing async runtime
  • Rayon team for data parallelism made easy
  • All contributors to the Rust ecosystem

Happy concurrent programming with Rust! ๐Ÿฆ€

About

๐Ÿฆ€ A comprehensive collection of Rust asynchronous and concurrent programming examples

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages