Welcome back to CodeYourCraft! Today, we're diving into the fascinating world of Atomic Types in Rust. If you're new to Rust, don't worry - we'll start from the ground up.
Atomic types in Rust are data types that provide basic operations on single values in a thread-safe manner. They are essential for multithreaded programming to prevent data races.
Rust provides four basic atomic types:
AtomicU8: Unsigned 8-bit integerAtomicI8: Signed 8-bit integerAtomicU32: Unsigned 32-bit integerAtomicI32: Signed 32-bit integerLet's create some simple examples using these atomic types:
use std::sync::atomic::{AtomicU8, Ordering};
let counter = AtomicU8::new(0);
// Increment counter
counter.fetch_add(1, Ordering::SeqCst);
// Get current value
let current_value = counter.load(Ordering::SeqCst);
print!("Counter: {current_value}");In this example, we've created an AtomicU8 variable named counter and initialized it to 0. The fetch_add function increments the counter, and load function retrieves its current value. The Ordering::SeqCst ensures sequential consistency.
use std::sync::atomic::{AtomicI32, Ordering};
let counter = AtomicI32::new(0);
// Increment counter
counter.fetch_add(1, Ordering::SeqCst);
// Get current value
let current_value = counter.load(Ordering::SeqCst);
print!("Counter: {current_value}");In this example, we've used AtomicI32 instead of AtomicU8. The rest of the code remains the same.
What does `AtomicU8` represent?
Stay tuned for more in-depth discussions on Atomic Types in Rust. Happy learning! 🚀💻