Thread_safe_containers
Thread-Safe Containers
Section titled “Thread-Safe Containers”Thread-safe containers provide built-in synchronization.
std::atomic
Section titled “std::atomic”#include <atomic>
std::atomic<int> counter(0);
void increment() { counter.fetch_add(1); // Atomic increment}Thread-Safe Wrappers
Section titled “Thread-Safe Wrappers”#include <mutex>#include <vector>
template<typename T>class ThreadSafeVector {private: std::vector<T> data; mutable std::mutex mtx;
public: void push_back(const T& value) { std::lock_guard<std::mutex> lock(mtx); data.push_back(value); }
T get(size_t index) const { std::lock_guard<std::mutex> lock(mtx); return data.at(index); }};Lock-Free Containers (C++20)
Section titled “Lock-Free Containers (C++20)”#include <atomic>
// Simple lock-free stacktemplate<typename T>class LockFreeStack { struct Node { T data; Node* next; };
std::atomic<Node*> head;
public: void push(T value) { Node* newNode = new Node{value, head.load()}; while (!head.compare_exchange_weak(newNode->next, newNode)); }};