Skip to content

Thread_safe_containers

Thread-safe containers provide built-in synchronization.

#include <atomic>
std::atomic<int> counter(0);
void increment() {
counter.fetch_add(1); // Atomic increment
}
#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);
}
};
#include <atomic>
// Simple lock-free stack
template<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));
}
};