17. Concurrency

17:1 The Rust programming language provides features for concurrent programming without data races, whose rules are presented in this chapter.

Legality Rules

17:2 A data race is a scenario where two or more threads access a shared memory location concurrently without any synchronization, where one of the accesses is a modification.

Undefined Behavior

17:3 It is undefined behavior if two or more threads engage in a data race.

17.1. Send and Sync

Legality Rules

17.1:1 The Rust programming language provides the core::marker::Send and core::marker::Sync traits for preventing data races at the type level.

17.1:2 A send type is a type that implements the core::marker::Send trait.

17.1:3 An abstract data type automatically implements the core::marker::Send trait if the types of all its fields are send types.

17.1:4 A send type shall have values that are safe to transfer across thread boundaries.

17.1:5 A sync type is a type that implements the core::marker::Sync trait.

17.1:6 An abstract data type automatically implements the core::marker::Sync trait if the types of all its fields are sync types.

17.1:7 A sync type shall have values that are allowed to be shared across multiple threads at any given time without incurring data races.

17.2. Atomics

Legality Rules

17.2:1 An atomic type is a type defined in module core::sync::atomic. Atomic types provide primitive shared-memory communication between threads.

17.2:2 Atomic types are related to types as follows:

17.2:3

Type

Atomic Type

17.2:4

bool

core::sync::atomic::AtomicBool

17.2:5

i8

core::sync::atomic::AtomicI8

17.2:6

i16

core::sync::atomic::AtomicI16

17.2:7

i32

core::sync::atomic::AtomicI32

17.2:8

i64

core::sync::atomic::AtomicI64

17.2:9

isize

core::sync::atomic::AtomicIsize

17.2:10

*mut T

core::sync::atomic::AtomicPtr

17.2:11

u8

core::sync::atomic::AtomicU8

17.2:12

u16

core::sync::atomic::AtomicU16

17.2:13

u32

core::sync::atomic::AtomicU32

17.2:14

u64

core::sync::atomic::AtomicU64

17.2:15

usize

core::sync::atomic::AtomicUsize

17.3. Asynchronous Computation

Legality Rules

17.3:1 The Rust programming language provides asynchronous computation through module core::task and the core::future::Future trait.

17.3:2 A future represents a value of a type that implements the core::future::Future trait which may not have finished computing yet.

17.3:3 The computed value of a future is obtained by using an await expression or by invoking core::future::Future::poll.

17.3:4 core::future::Future::poll shall not be invoked on a future that has already returned core::task::Poll::Ready.