Lock-free data structures are a crucial aspect of concurrent programming, enabling multiple threads to operate on shared data without the risk of deadlocks or contention. By using atomic operations and careful design, developers can create efficient and scalable data structures that perform well in multithreaded environments.
// A simple lock-free stack implementation in C++
#include
template
class LockFreeStack {
private:
struct Node {
T data;
Node* next;
Node(T data) : data(data), next(nullptr) {}
};
std::atomic head;
public:
LockFreeStack() : head(nullptr) {}
void push(T value) {
Node* newNode = new Node(value);
newNode->next = head.load();
while (!head.compare_exchange_weak(newNode->next, newNode)) {
// Loop until we successfully set the new head
}
}
bool pop(T& result) {
Node* oldHead = head.load();
while (oldHead != nullptr && !head.compare_exchange_weak(oldHead, oldHead->next)) {
// Loop until we successfully pop the head
}
if (oldHead == nullptr) {
return false; // Stack was empty
}
result = oldHead->data;
delete oldHead; // Free the memory
return true;
}
};
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?