Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 40: Atomic Operations (std::atomi | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

Lesson 40 of 45

·C++

Lesson 40: Atomic Operations (std::atomic)

10 min

Course progress89%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • Atomic types and operations
  • Memory order semantics
  • Lock‑free programming basics
  • When to prefer atomics over mutexes

Atomic Operations (std::atomic)

std::atomic provides lock‑free primitives for safe concurrent access to simple data types. They guarantee atomic read‑modify‑write operations and avoid the overhead of mutexes for fine‑grained synchronization.


Example: Atomic counter increment

#include <atomic>
#include <thread>

std::atomic<int> atomicCounter{0};

void inc(int n) {
    for (int i = 0; i < n; ++i) {
        atomicCounter.fetch_add(1, std::memory_order_relaxed);
    }
}

int main() {
    std::thread t1(inc, 1000);
    std::thread t2(inc, 1000);
    t1.join();
    t2.join();
    std::cout << \"Atomic counter: \" << atomicCounter.load() << '\
';
    return 0;
}

Compare‑exchange example

std::atomic<int> flag{0};
int expected = 0;
if (flag.compare_exchange_strong(expected, 1)) {
    // We successfully set flag from 0 to 1
    std::cout << \"Acquired flag\
\";
}

Tip: Use std::atomic_flag for a simple spin‑lock, but be wary of busy‑waiting.


<Alert type="warning">Atomic operations are only safe for trivially copyable types. For complex structures, protect them with mutexes or design lock‑free data structures.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 39: Mutexes and Locks (std::mutex, std::lock_guard)Continue to lesson 41Lesson 41: Modern C++ Features (C++11/14/17/20)Back to C++ Course curriculum