Rust Concurrency - rFronteddu/general_wiki GitHub Wiki

Handling concurrent programming safely and efficiently is another of Rust’s major goals. By leveraging ownership and type checking, many concurrency errors are compile-time errors in Rust rather than runtime errors.

Rust offers a variety of tools for modeling problems in whatever way is appropriate for your situation and requirements.

  • How to create threads to run multiple pieces of code at the same time
  • Message-passing concurrency, where channels send messages between threads
  • Shared-state concurrency, where multiple threads have access to some piece of data using mutex
  • The Sync and Send traits, which extend Rust’s concurrency guarantees to user-defined types as well as types provided by the standard library

Async and Await

Since we understand our programs at a much more granular level than the operating system does, we can spot lots of opportunities for concurrency that the operating system cannot see.

We could avoid blocking our main thread by spawning a dedicated thread to download each file. However, we would eventually find that the overhead of those threads was a problem. It would also be nicer if the call were not blocking in the first place. Last but not least, it would be better if we could write in the same direct style we use in blocking code. Something like this:

let data = fetch_data_from(url).await;
println!("{data}");

That is exactly what Rust’s async abstraction gives us. When an individual works on several different tasks before any of them is complete, this is concurrency. When you agree to split up a group of tasks between the people on the team, with each person taking one task and working on it alone, this is parallelism. Each person on the team can make progress at the exact same time. With both of these situations, you might have to coordinate between different tasks.