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