rayon README

The project's README from github.com/rayon-rs/rayon. As one markdown file: README.md.

Rayon

Rayon crate Rayon documentation minimum rustc 1.85 build status

Rayon is a data-parallelism library for Rust. It is extremely lightweight and makes it easy to convert a sequential computation into a parallel one. It also guarantees data-race freedom. (You may also enjoy this blog post about Rayon, which gives more background and details about how it works, or this video, from the Rust Belt Rust conference.) Rayon is available on crates.io, and API documentation is available on docs.rs.

Parallel iterators and more

Rayon makes it drop-dead simple to convert sequential iterators into parallel ones: usually, you just change your foo.iter() call into foo.par_iter(), and Rayon does the rest:

use rayon::prelude::*;
fn sum_of_squares(input: &[i32]) -> i32 {
    input.par_iter() // <-- just change that!
         .map(|&i| i * i)
         .sum()
}

Parallel iterators take care of deciding how to divide your data into tasks; it will dynamically adapt for maximum performance. If you need more flexibility than that, Rayon also offers the join and scope functions, which let you create parallel tasks on your own. For even more control, you can create custom thread pools rather than using Rayon's default, global thread pool.

No data races

You may have heard that parallel execution can produce all kinds of crazy bugs. Well, rest easy. Rayon's APIs all guarantee data-race freedom, which generally rules out most parallel bugs (though not all). In other words, if your code compiles, it typically does the same thing it did before.

For the most part, parallel iterators in particular are guaranteed to produce the same results as their sequential counterparts. One caveat: If your iterator has side effects (for example, sending methods to other threads through a Rust channel or writing to disk), those side effects may occur in a different order. Note also that, in some cases, parallel iterators offer alternative versions of the sequential iterator methods that can have higher performance.

Using Rayon

Rayon is available on crates.io. The recommended way to use it is to add a line into your Cargo.toml such as:

[dependencies]
rayon = "1.12"

To use the parallel iterator APIs, a number of traits have to be in scope. The easiest way to bring those things into scope is to use the Rayon prelude. In each module where you would like to use the parallel iterator APIs, just add:

use rayon::prelude::*;

Rayon currently requires rustc 1.85.0 or greater.

Usage with WebAssembly

By default, when building to WebAssembly, Rayon will treat it as any other platform without multithreading support and will fall back to sequential iteration. This allows existing code to compile and run successfully with no changes necessary, but it will run slower as it will only use a single CPU core.

You can build Rayon-based projects with proper multithreading support for the Web, but you'll need an adapter and some project configuration to account for differences between WebAssembly threads and threads on the other platforms.

Check out the wasm-bindgen-rayon docs for more details.

Contribution

Rayon is an open source project! If you'd like to contribute to Rayon, check out the list of "help wanted" issues. These are all (or should be) issues that are suitable for getting started, and they generally include a detailed set of instructions for what to do. Please ask questions if anything is unclear! Also, check out the Guide to Development page on the wiki. Note that all code submitted in PRs to Rayon is assumed to be licensed under Rayon's dual MIT/Apache 2.0 licensing.

Quick demo

To see Rayon in action, check out the rayon-demo directory, which includes a number of demos of code using Rayon. For example, run this command to get a visualization of an N-body simulation. To see the effect of using Rayon, press s to run sequentially and p to run in parallel.

> cd rayon-demo
> cargo run --release -- nbody visualize

For more information on demos, try:

> cd rayon-demo
> cargo run --release -- --help

Other questions?

See the Rayon FAQ.

License

Rayon is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See LICENSE-APACHE and LICENSE-MIT for details. Opening a pull request is assumed to signal agreement with these licensing terms.

rayon (rayon-rs/rayon)

Searching Database…

13.4K ·GitHub
Что это такое?Rayon — это библиотека параллельной обработки данных для Rust. Она предельно легковесна и позволяет легко превратить последовательное вычисление в параллельное, с гарантией отсутствия гонок за данные.
Это приложение, которое я запускаю, или библиотека для кода?Библиотека: вы добавляете её как зависимость в свой Rust-проект и вызываете её API из своего кода. Устанавливать и запускать отдельно ничего не нужно — крейт лежит на crates.io, а документация по API — на docs.rs.
С чего начать использовать её в проекте?Добавьте строку с rayon в свой Cargo.toml, а затем подключайте прелюдию Rayon в каждом модуле, где нужны API параллельных итераторов, чтобы необходимые трейты были в области видимости.
Нужно ли что-то особенное установить для работы с ней?Нужен только свежий инструментарий Rust: на данный момент Rayon требует rustc 1.85.0 или новее, а это покрывает любой актуальный стабильный дистрибутив.
Параллельная версия будет вести себя в точности как мой последовательный код?В основном да: отсутствие гонок за данные гарантировано, а параллельные итераторы дают те же результаты, что и последовательные. Единственная оговорка: побочные эффекты вроде отправки в каналы или записи на диск могут происходить в другом порядке.
Можно ли бесплатно использовать её в своих проектах?Да — Rayon распространяется на условиях лицензии MIT и Apache License (версия 2.0) одновременно.
Есть ли быстрый способ увидеть Rayon в действии?Да — в каталоге rayon-demo есть несколько демо, например визуализация N-телесной симуляции. Нажмите s, чтобы запустить её последовательно, и p, чтобы запустить параллельно, и сравните разницу.
Почему лучше взять Rayon, чем вручную возиться с потоками?В этом и есть вся его идея: распараллеливание последовательных итераторов описывается как максимально простое, а API гарантируют отсутствие гонок за данные, поэтому код, который успешно компилируется, обычно ведёт себя как раньше — и вам не нужно самому делить задачи по потокам.
Насколько проект зрелый?Rayon есть на GitHub с октября 2014 года, у него около 13 400 звёзд. В README также есть ссылки на сопроводительную статью в блоге, доклад на конференции и FAQ, где разобраны другие вопросы.
What are similar projects?conc, taskflow, tokio, perry, bend, compio, muduo, concurrentqueue
Creator
rayon-rs
Size
3.6 MB
Stars
13.4K
Updated
CommitAug 28
Age
12y
Commits · 90 Days