732-C++实现线程安全的链式栈

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;
		//std::this_thread::sleep_for(std::chrono::seconds(1));
		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)//线程1
{
	for (int i = 0; i < 10; i += 2)
	{
		cout << i << endl;
		s.push(i);
	}
}
void thread_funb(Stack<int>& s)//线程2
{
	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;
}

运行截图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林林林ZEYU

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值