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

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C++ Course

Lesson 35 of 45 · C++

Lesson 40: Atomic Operations (std::atomic)

Duration: 10 min

Atomic Operations (std::atomic)\n\nstd::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.\n\n---\n\n## Example: Atomic counter increment\ncpp\n#include <atomic>\n#include <thread>\n\nstd::atomic<int> atomicCounter{0};\n\nvoid inc(int n) {\n for (int i = 0; i < n; ++i) {\n atomicCounter.fetch_add(1, std::memory_order_relaxed);\n }\n}\n\nint main() {\n std::thread t1(inc, 1000);\n std::thread t2(inc, 1000);\n t1.join();\n t2.join();\n std::cout << \"Atomic counter: \" << atomicCounter.load() << '\\n';\n return 0;\n}\n\n\n## Compare‑exchange example\ncpp\nstd::atomic<int> flag{0};\nint expected = 0;\nif (flag.compare_exchange_strong(expected, 1)) {\n // We successfully set flag from 0 to 1\n std::cout << \"Acquired flag\\n\";\n}\n\n\n> Tip: Use std::atomic_flag for a simple spin‑lock, but be wary of busy‑waiting.\n\n---\n\n<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.

Previous: Lesson 4: Variables and Data TypesNext: Lesson 41: Modern C++ Features (C++11/14/17/20)