C++实现线程安全的链式栈
#include <iostream>
#include<mutex>
#include<thread>
using namespace std;
struct empty_stack : std::exception
{
const char* what() const throw();
};
template<class T>
class Stack
{
private:
struct StackNode
{
T value;
StackNode* next;
};
StackNode* Buynode()
{
StackNode* s = (StackNode*)malloc(sizeof(StackNode));
if (NULL == s) exit(EXIT_FAILURE);
memset(s, 0, sizeof(StackNode));
return s;
}
void Freenode(StackNode* p)
{
free(p);
}
private:
StackNode* base;
size_t cursize;
mutable std::mutex mtx;
Stack(const Stack&);
Stack& operator=(const Stack&);
public:
Stack() :base(nullptr) {}
~Stack() { clear(); }
size_t get_size() const
{
std::lock_guard<std::mutex> lock(mtx);
return cursize;
}
bool is_empty() const
{
return get_size() == 0;
}
void clear()
{
std::lock_guard<std::mutex> lock(mtx);
while (base != nullptr)
{
StackNode* q = base;
base = q->next;
Freenode(q);
}
cursize = 0;
}
void push(const T& x)
{
std::lock_guard<std::mutex> lock(mtx);
StackNode* s = Buynode();
new(&(s->value)) T(x);
s->next = base;
base = s;
cursize += 1;
}
T& top()
{
std::lock_guard<std::mutex> lock(mtx);
return base->value;
}
const T& top()const
{
std::lock_guard<std::mutex> lock(mtx);
return base->value;
}
void pop()
{
std::lock_guard<std::mutex> lock(mtx);
if (base != nullptr)
{
StackNode* q = base;
base = q->next;
Freenode(q);
cursize -= 1;
}
}
};
void thread_funa(Stack<int>& s)
{
for (int i = 0; i < 10; i += 2)
{
cout << i << endl;
s.push(i);
}
}
void thread_funb(Stack<int>& s)
{
for (int i = 1; i < 10; i += 2)
{
cout << i << endl;
s.push(i);
}
}
int main()
{
Stack<int> ist;
thread ta(thread_funa, std::ref(ist));
thread tb(thread_funb, std::ref(ist));
ta.join();
tb.join();
cout << "thread end" << endl;
while (!ist.is_empty())
{
int x = ist.top();
ist.pop();
cout << x << endl;
}
return 0;
}
运行截图