๐ฆ A comprehensive collection of Rust asynchronous and concurrent programming examples, demonstrating various patterns, primitives, and best practices.
- Features
- Quick Start
- Examples
- Dependencies
- Performance Benchmarks
- Learning Resources
- Contributing
- License
- Basic thread creation and management
- Thread-safe data sharing with
ArcandMutex - Data parallelism with Rayon
- Scoped threads
- Work-stealing scheduling
Mutex- Mutual exclusionRwLock- Reader-writer locksCondvar- Condition variablesBarrier- Thread synchronization barriersOnceCell- One-time initializationparking_lot- High-performance locking primitives
async/awaitfundamentalsFutureandStreamabstractions- Async task management
- Timeout handling
- Stream processing with buffering
- Task selection with
select! - Async synchronization primitives
- Standard library
mpscchannels - Multi-producer, single-consumer patterns
crossbeamchannelsflumehigh-performance channels- Work queue patterns
- Atomic counters
- Atomic booleans
- Compare-and-swap operations
- Memory ordering
- Lock-free data structures
- Concurrent merge sort
- Async merge sort
- Concurrent quicksort
- Parallel search
- Producer-consumer patterns
- Map-Reduce patterns
- Rust 1.70+ (with
async/awaitsupport) - Cargo package manager
# 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# 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// 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();// 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;// 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);use std::sync::atomic::{AtomicUsize, Ordering};
let counter = AtomicUsize::new(0);
counter.fetch_add(1, Ordering::SeqCst);
let value = counter.load(Ordering::SeqCst);- 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
Run performance comparisons between different approaches:
cargo run benchmarksBenchmarks include:
- Thread vs Async task performance
- Different lock implementations
- Channel performance comparison
- Atomic vs Mutex performance
- The Rust Programming Language - Chapter 16: Fearless Concurrency
- Rust Atomics and Locks by Mara Bos
- Programming Rust - Chapters 19-20
# Run all tests
cargo test
# Run tests with output
cargo test -- --nocapture
# Run specific module tests
cargo test threads
cargo test async_programmingsrc/
โโโ 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
- Add your example function to the appropriate module
- Update the
run_examples()function in that module - Add tests for your example
- Update the README if needed
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.
- Follow Rust naming conventions
- Add comprehensive documentation
- Include tests for new examples
- Ensure code is formatted with
cargo fmt - Run
cargo clippyto check for common mistakes
This project is licensed under the MIT License - see the LICENSE file for details.
- 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! ๐ฆ