#include <atomic>
#include <thread>
#include <iostream>
using namespace std;
#define THREAD_NUM 32 // 测试用的线程数
template<typename T>
class LockFreeStack {
public:
LockFreeStack() {
head_ = nullptr;
}
void Push(const T& value) {
Node* newNode = new Node(value);
// 将新节点的 next 指针指向 head_
newNode->next = head_;
while(!atomic_compare_exchange_weak(&head_, &newNode->next, newNode));
}
bool Pop(T& item) {
Node* oldHead = head_;
do {
if(!oldHead) {
return false; // 空栈,返回 false 表示操作失败
}
} while(!atomic_compare_exchange_weak(&head_, &oldHead, oldHead->next));
item = oldHead->data;
delete oldHead;
return true;
}
private:
struct Node {
T data;
Node* next;
Node(const T& data) : data(data), next(nullptr) {}
};
atomic<Node*> head_;
};
LockFreeStack<int> stack;
void TestPush(int id) {
for(int i = 0; i < 1000; ++i) {
stack.Push(i * THREAD_NUM + id);
}
}
void TestPop() {
int item;
int count = 0;
while(stack.Pop(item)) {
count++;
}
cout << "Thread " << std::this_thread::get_id() << " got " << count << " items." << endl;
}
int main() {
thread producers[THREAD_NUM];
for(int i = 0; i < THREAD_NUM; ++i) {
producers[i] = thread(TestPush, i);
}
thread consumer1(TestPop);
thread consumer2(TestPop);
for(int i = 0; i < THREAD_NUM; ++i) {
producers[i].join();
}
consumer1.join();
consumer2.join();
return 0;
}
C++11 atomic_exchange 实现无锁链表
于 2022-11-28 20:13:45 首次发布