#include<thread>
#include<iostream>
using namespace std;
using namespace this_thread;
struct empty_stack :exception
{
//重写异常处理
const char* what() const noexcept
{
return "stack is empty!";
}
};
template <class T>
class threadsafe_stack
{
private:
mutable mutex m;
stack<T> date;
public:
//构造函数
threadsafe_stack() {}
//拷贝构造
threadsafe_stack(const threadsafe_stack& other)
{
lock_guard<mutex> locks(other.m);
date = other.date;
}
threadsafe_stack& operator = (const threadsafe_stack&) = delete;
//万金油函数
bool empty() const
{
lock_guard<mutex> locks(m);
return date.empty();
}
size_t size() const
{
lock_guard<mutex> locks(m);
return date.size();
}
//存储数据
void push(T value)
{
lock_guard<mutex> locks(m); //加锁
date.push(move(value));
}
//取数据
void pop(T& value)
{
lock_guard<mutex> locks(m);
if (date.empty())
{
throw empty_stack();
}
value = move(date.top());
}
};
//封装线程函数
//插入数据
void insertDate(threadsafe_stack<int>& stack,int value)
{
stack.push(value);
}
void daleteDate(threadsafe_stack<int> &stack)
{
try
{
int value = 0;
stack.pop(value);
printf("date:%d\n",value);
}
catch(empty_stack re)
{
printf("%s\n",re.what());
}
}
int main()
{
vector<thread> t;
threadsafe_stack<int> test;
for (int i = 0; i < 5; i++)
{
t.push_back(thread(insertDate,ref(test),i));
t.push_back(thread(daleteDate, ref(test)));
}
for (auto& v : t)
{
v.join();
}
cout << "size:" << test.size() << endl;
return 0;
}
第十四课:C++多线程的线程安全栈
最新推荐文章于 2024-08-15 05:02:54 发布