You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/concurrency.md
+51-2Lines changed: 51 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -12,12 +12,61 @@ r[concurrency.send-and-sync]
12
12
r[concurrency.send-and-sync.intro]
13
13
The [`Send`] and [`Sync`] traits are [unsafe traits] used by the Rust type system to track which types can be safely used across thread boundaries.
14
14
15
-
These traits are [marker traits] with no methods. Implementing them asserts that a type has the intrinsic properties required for safe concurrent use. The compiler automatically implements these traits for most types when possible, but they can also be implemented manually. Providing an incorrect manual implementation can cause [undefined behavior].
15
+
These traits are [marker traits] with no methods. Implementing them (whether manually or via the compiler's automatic implementation) asserts that a type has the intrinsic properties required for safe concurrent use.
16
+
17
+
Library functions that require types that can be sent across threads require [`Send`].
18
+
```rust
19
+
// This will compile successfully
20
+
// A type is `Send` if it can be safely transferred to another thread.
21
+
fnassert_send<T:Send>() {}
22
+
23
+
fnmain() {
24
+
assert_send::<i32>(); // primitive types are Send
25
+
assert_send::<Vec<u8>>(); // Vec<T> is Send if T is Send
26
+
}
27
+
```
28
+
29
+
```rust
30
+
// This will not compile
31
+
// A type containing `Rc<T>` is not `Send`.
32
+
usestd::rc::Rc;
33
+
34
+
fnassert_send<T:Send>() {}
35
+
36
+
fnmain() {
37
+
let_x=Rc::new(1);
38
+
assert_send::<Rc<i32>>(); //~ error[E0277] `Rc<i32>` cannot be sent between threads safely
39
+
}
40
+
```
41
+
42
+
Library functions that require types that can be accessed concurrently from multiple threads require [`Sync`].
43
+
```rust
44
+
// This will compile successfully
45
+
// A type is `Sync` if it can be safely referenced from multiple threads.
46
+
fnassert_sync<T:Sync>() {}
47
+
48
+
fnmain() {
49
+
assert_sync::<i32>(); // i32 is Sync
50
+
assert_sync::<&'staticstr>(); // string slices are Sync
51
+
assert_sync::<std::sync::Arc<i32>>(); // Arc<T> is Sync if T is Sync
52
+
}
53
+
```
54
+
55
+
```rust
56
+
// This will not compile
57
+
// A type containing `Cell<T>` is not `Sync`.
58
+
usestd::cell::Cell;
59
+
60
+
fnassert_sync<T:Sync>() {}
61
+
62
+
fnmain() {
63
+
assert_sync::<Cell<i32>>(); //~ error[E0277] `*const i32` cannot be shared between threads safely
0 commit comments