Atomic Types in Rust Tutorial 🎯

beginner
23 min

Atomic Types in Rust Tutorial 🎯

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.

What are Atomic Types? 📝

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.

Understanding Basic Atomic Types 💡

Rust provides four basic atomic types:

  1. AtomicU8: Unsigned 8-bit integer
  2. AtomicI8: Signed 8-bit integer
  3. AtomicU32: Unsigned 32-bit integer
  4. AtomicI32: Signed 32-bit integer

Let's create some simple examples using these atomic types:

Example 1: AtomicU8

rust
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.

Example 2: AtomicI32

rust
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.

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

What does `AtomicU8` represent?

Stay tuned for more in-depth discussions on Atomic Types in Rust. Happy learning! 🚀💻