Debian Codegraph @

third_party/rust/cache-padded/README.md

raw
1 # cache-padded
2
3 [![Build](https://github.com/smol-rs/cache-padded/workflows/Build%20and%20test/badge.svg)](
4 https://github.com/smol-rs/cache-padded/actions)
5 [![License](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg)](
6 https://github.com/smol-rs/cache-padded)
7 [![Cargo](https://img.shields.io/crates/v/cache-padded.svg)](
8 https://crates.io/crates/cache-padded)
9 [![Documentation](https://docs.rs/cache-padded/badge.svg)](
10 https://docs.rs/cache-padded)
11
12 Prevent false sharing by padding and aligning to the length of a cache line.
13
14 In concurrent programming, sometimes it is desirable to make sure commonly accessed shared data
15 is not all placed into the same cache line. Updating an atomic value invalides the whole cache
16 line it belongs to, which makes the next access to the same cache line slower for other CPU
17 cores. Use `CachePadded` to ensure updating one piece of data doesn't invalidate other cached
18 data.
19
20 ## Size and alignment
21
22 Cache lines are assumed to be N bytes long, depending on the architecture:
23
24 * On x86-64 and aarch64, N = 128.
25 * On all others, N = 64.
26
27 Note that N is just a reasonable guess and is not guaranteed to match the actual cache line
28 length of the machine the program is running on.
29
30 The size of `CachePadded<T>` is the smallest multiple of N bytes large enough to accommodate
31 a value of type `T`.
32
33 The alignment of `CachePadded<T>` is the maximum of N bytes and the alignment of `T`.
34
35 ## Examples
36
37 Alignment and padding:
38
39 ```rust
40 use cache_padded::CachePadded;
41
42 let array = [CachePadded::new(1i8), CachePadded::new(2i8)];
43 let addr1 = &*array[0] as *const i8 as usize;
44 let addr2 = &*array[1] as *const i8 as usize;
45
46 assert!(addr2 - addr1 >= 64);
47 assert_eq!(addr1 % 64, 0);
48 assert_eq!(addr2 % 64, 0);
49 ```
50
51 When building a concurrent queue with a head and a tail index, it is wise to place indices in
52 different cache lines so that concurrent threads pushing and popping elements don't invalidate
53 each other's cache lines:
54
55 ```rust
56 use cache_padded::CachePadded;
57 use std::sync::atomic::AtomicUsize;
58
59 struct Queue<T> {
60 head: CachePadded<AtomicUsize>,
61 tail: CachePadded<AtomicUsize>,
62 buffer: *mut T,
63 }
64 ```
65
66 ## License
67
68 Licensed under either of
69
70 * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
71 * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
72
73 at your option.
74
75 #### Contribution
76
77 Unless you explicitly state otherwise, any contribution intentionally submitted
78 for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
79 dual licensed as above, without any additional terms or conditions.