Top Related Projects
A runtime for writing reliable asynchronous applications with Rust. Provides I/O, networking, scheduling, timers, ...
Rayon: A data parallelism library for Rust
A small and fast async runtime for Rust
Async version of the Rust standard library
Actor framework for Rust.
Quick Overview
Crossbeam is a Rust library that provides a set of tools for concurrent programming. It offers efficient and safe data structures, synchronization primitives, and utilities designed to make concurrent and parallel programming in Rust easier and more robust.
Pros
- Provides highly optimized concurrent data structures and primitives
- Offers safe abstractions for complex concurrency patterns
- Well-documented and actively maintained
- Integrates seamlessly with Rust's ownership and borrowing system
Cons
- Learning curve for developers new to concurrent programming
- Some advanced features may require understanding of low-level concurrency concepts
- Occasional breaking changes between major versions
- May introduce additional complexity to simpler projects
Code Examples
- Using a concurrent queue:
use crossbeam::queue::ArrayQueue;
let queue = ArrayQueue::new(100);
queue.push(1).unwrap();
assert_eq!(queue.pop(), Some(1));
- Scoped threads for easier lifetime management:
use crossbeam::scope;
let mut vec = vec![1, 2, 3];
scope(|s| {
s.spawn(|_| {
vec[0] += 10;
});
s.spawn(|_| {
vec[1] += 20;
});
}).unwrap();
assert_eq!(vec, [11, 22, 3]);
- Using an atomic cell for lock-free updates:
use crossbeam::atomic::AtomicCell;
let cell = AtomicCell::new(5);
cell.fetch_add(1);
assert_eq!(cell.load(), 6);
Getting Started
To use Crossbeam in your Rust project, add the following to your Cargo.toml
:
[dependencies]
crossbeam = "0.8"
Then, in your Rust code, you can import and use Crossbeam's features:
use crossbeam::channel;
fn main() {
let (sender, receiver) = channel::unbounded();
sender.send("Hello, Crossbeam!").unwrap();
assert_eq!(receiver.recv(), Ok("Hello, Crossbeam!"));
}
This example demonstrates creating an unbounded channel, sending a message, and receiving it. Crossbeam offers many more concurrent programming tools that you can explore in its documentation.
Competitor Comparisons
A runtime for writing reliable asynchronous applications with Rust. Provides I/O, networking, scheduling, timers, ...
Pros of Tokio
- Full-featured asynchronous runtime with support for I/O, timers, and scheduling
- Extensive ecosystem with many compatible libraries and tools
- Built-in support for futures and async/await syntax
Cons of Tokio
- Steeper learning curve due to its comprehensive feature set
- Higher overhead for simple concurrent tasks compared to Crossbeam
- More complex setup required for basic usage
Code Comparison
Tokio example:
#[tokio::main]
async fn main() {
println!("Hello from Tokio!");
tokio::time::sleep(Duration::from_secs(1)).await;
}
Crossbeam example:
fn main() {
crossbeam::scope(|s| {
s.spawn(|_| println!("Hello from Crossbeam!"));
}).unwrap();
}
Key Differences
- Tokio focuses on asynchronous programming, while Crossbeam emphasizes lock-free data structures and concurrent utilities
- Tokio provides a complete runtime for async tasks, whereas Crossbeam offers lower-level concurrency primitives
- Tokio is better suited for I/O-bound applications, while Crossbeam excels in CPU-bound concurrent scenarios
Use Cases
- Choose Tokio for network programming, web servers, and complex asynchronous workflows
- Opt for Crossbeam when dealing with shared memory, lock-free data structures, or fine-grained concurrency control
Community and Ecosystem
- Tokio has a larger ecosystem with more third-party libraries and integrations
- Crossbeam is more focused and specialized, with a smaller but dedicated community
Rayon: A data parallelism library for Rust
Pros of Rayon
- Higher-level abstraction for parallel programming, making it easier to parallelize existing code
- Automatic work-stealing scheduler for efficient load balancing
- Seamless integration with iterators and collections
Cons of Rayon
- Less fine-grained control over thread management and synchronization
- May introduce overhead for simple parallelization tasks
- Limited to data parallelism, not suitable for task-based concurrency
Code Comparison
Rayon:
use rayon::prelude::*;
let result: Vec<i32> = (0..1000).into_par_iter()
.map(|i| i * i)
.collect();
Crossbeam:
use crossbeam::scope;
let mut result = vec![0; 1000];
scope(|s| {
for chunk in result.chunks_mut(100) {
s.spawn(|_| {
for (i, item) in chunk.iter_mut().enumerate() {
*item = i * i;
}
});
}
});
Rayon provides a more concise and intuitive API for parallel operations, while Crossbeam offers more control over thread management and synchronization primitives. Rayon is better suited for data parallelism tasks, whereas Crossbeam excels in scenarios requiring fine-grained control over concurrent operations.
A small and fast async runtime for Rust
Pros of smol
- Provides a complete async runtime with a simpler API
- Offers built-in async networking primitives
- Designed for small, efficient applications with minimal overhead
Cons of smol
- Less mature and battle-tested compared to Crossbeam
- Narrower focus on async programming, less suitable for general concurrency
Code Comparison
smol example:
use smol::Timer;
use std::time::Duration;
smol::block_on(async {
Timer::after(Duration::from_secs(1)).await;
println!("One second has passed");
});
Crossbeam example:
use crossbeam::channel;
use std::thread;
use std::time::Duration;
let (s, r) = channel::bounded(0);
thread::spawn(move || {
thread::sleep(Duration::from_secs(1));
s.send(()).unwrap();
});
r.recv().unwrap();
println!("One second has passed");
Summary
smol is a lightweight async runtime focused on simplicity and efficiency, while Crossbeam is a more comprehensive concurrency library with a broader range of synchronization primitives. smol is better suited for async-heavy applications, while Crossbeam excels in scenarios requiring fine-grained control over concurrent operations across multiple threads.
Async version of the Rust standard library
Pros of async-std
- Provides a complete async runtime and ecosystem
- Offers a familiar API similar to the Rust standard library
- Supports both async and blocking operations seamlessly
Cons of async-std
- Higher overhead for simple concurrent tasks
- Steeper learning curve for developers new to async programming
- May introduce additional complexity for projects that don't require async functionality
Code Comparison
async-std example:
use async_std::task;
async fn example() {
println!("Hello, world!");
}
fn main() {
task::block_on(example());
}
Crossbeam example:
use crossbeam::channel;
fn main() {
let (sender, receiver) = channel::unbounded();
sender.send("Hello, world!").unwrap();
println!("{}", receiver.recv().unwrap());
}
Key Differences
- Crossbeam focuses on low-level concurrency primitives, while async-std provides a high-level async runtime
- async-std is built around the async/await paradigm, whereas Crossbeam uses traditional threading models
- Crossbeam is generally more suitable for CPU-bound tasks, while async-std excels in I/O-bound scenarios
Use Cases
- Choose async-std for projects heavily reliant on asynchronous operations or network I/O
- Opt for Crossbeam when dealing with parallel computations or fine-grained concurrency control
Community and Ecosystem
- Both projects have active communities and are well-maintained
- async-std has a growing ecosystem of compatible libraries
- Crossbeam is widely used and has a proven track record in production environments
Actor framework for Rust.
Pros of Actix
- Full-featured web framework with built-in HTTP server
- High performance and scalability for web applications
- Extensive ecosystem with plugins and middleware
Cons of Actix
- Steeper learning curve due to its comprehensive feature set
- Heavier dependency footprint compared to Crossbeam
- More opinionated architecture, which may limit flexibility in some cases
Code Comparison
Actix (web server example):
use actix_web::{web, App, HttpResponse, HttpServer};
async fn index() -> HttpResponse {
HttpResponse::Ok().body("Hello world!")
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().route("/", web::get().to(index)))
.bind("127.0.0.1:8080")?
.run()
.await
}
Crossbeam (concurrent queue example):
use crossbeam::queue::ArrayQueue;
let queue = ArrayQueue::new(100);
queue.push(1).unwrap();
queue.push(2).unwrap();
assert_eq!(queue.pop(), Some(1));
assert_eq!(queue.pop(), Some(2));
While both Actix and Crossbeam are Rust libraries, they serve different purposes. Actix is a web framework focused on building web applications, while Crossbeam provides low-level concurrency primitives. The choice between them depends on the specific requirements of your project.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Crossbeam
This crate provides a set of tools for concurrent programming:
Atomics
AtomicCell
, a thread-safe mutable memory location.(no_std)AtomicConsume
, for reading from primitive atomic types with "consume" ordering.(no_std)
Data structures
deque
, work-stealing deques for building task schedulers.ArrayQueue
, a bounded MPMC queue that allocates a fixed-capacity buffer on construction.(alloc)SegQueue
, an unbounded MPMC queue that allocates small buffers, segments, on demand.(alloc)
Memory management
epoch
, an epoch-based garbage collector.(alloc)
Thread synchronization
channel
, multi-producer multi-consumer channels for message passing.Parker
, a thread parking primitive.ShardedLock
, a sharded reader-writer lock with fast concurrent reads.WaitGroup
, for synchronizing the beginning or end of some computation.
Utilities
Backoff
, for exponential backoff in spin loops.(no_std)CachePadded
, for padding and aligning a value to the length of a cache line.(no_std)scope
, for spawning threads that borrow local variables from the stack.
Features marked with (no_std) can be used in no_std
environments.
Features marked with (alloc) can be used in no_std
environments, but only if alloc
feature is enabled.
Crates
The main crossbeam
crate just re-exports tools from
smaller subcrates:
crossbeam-channel
provides multi-producer multi-consumer channels for message passing.crossbeam-deque
provides work-stealing deques, which are primarily intended for building task schedulers.crossbeam-epoch
provides epoch-based garbage collection for building concurrent data structures.crossbeam-queue
provides concurrent queues that can be shared among threads.crossbeam-utils
provides atomics, synchronization primitives, scoped threads, and other utilities.
There is one more experimental subcrate that is not yet included in crossbeam
:
crossbeam-skiplist
provides concurrent maps and sets based on lock-free skip lists.
Usage
Add this to your Cargo.toml
:
[dependencies]
crossbeam = "0.8"
Compatibility
Crossbeam supports stable Rust releases going back at least six months, and every time the minimum supported Rust version is increased, a new minor version is released. Currently, the minimum supported Rust version is 1.61.
Contributing
Crossbeam welcomes contribution from everyone in the form of suggestions, bug reports, pull requests, and feedback. ð
If you need ideas for contribution, there are several ways to get started:
- Found a bug or have a feature request? Submit an issue!
- Issues and PRs labeled with feedback wanted need feedback from users and contributors.
- Issues labeled with good first issue are relatively easy starter issues.
RFCs
We also have the RFCs repository for more high-level discussion, which is the place where we brainstorm ideas and propose substantial changes to Crossbeam.
You are welcome to participate in any open issues or pull requests.
Learning resources
If you'd like to learn more about concurrency and non-blocking data structures, there's a list of learning resources in our wiki, which includes relevant blog posts, papers, videos, and other similar projects.
Another good place to visit is merged RFCs. They contain elaborate descriptions and rationale for features we've introduced to Crossbeam, but keep in mind that some of the written information is now out of date.
Conduct
The Crossbeam project adheres to the Rust Code of Conduct. This describes the minimum behavior expected from all contributors.
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Some Crossbeam subcrates have additional licensing notices. Take a look at other readme files in this repository for more information.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
Top Related Projects
A runtime for writing reliable asynchronous applications with Rust. Provides I/O, networking, scheduling, timers, ...
Rayon: A data parallelism library for Rust
A small and fast async runtime for Rust
Async version of the Rust standard library
Actor framework for Rust.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot