为并发设计数据结构是为了多个线程可以同时更好的使用此结构
设计并发数据结构的准则是什么
在设计并发数据结构时最主要的地方是应当注意到互斥元的使用位置。
最简单的方法就是在原始栈的每个函数内部开头添加一个互斥元,可以达到安全并发访问此数据结构的目的,但是这种情况下效率较低。
#include <mutex>
#include <stack>
#include <memory>
#include <exception>
using namespace std;
template<typename T>
class safe_stack{
private:
stack<T> sk;
mutex m_mutex;
public:
safe_stack(){}
safe_stack(int n, T value){
lock_guard<mutex> lg(m_mutex);
while(n --) sk.push(value);
}
safe_stack(safe_stack& other){
lock_guard<mutex> lg(m_mutex);
sk = other.sk;
}
safe_stack& operator=( safe_stack &other) = delete;
void push(T v){
lock_guard<mutex> lg(m_mutex);
sk.push(v);
}
T pop(){
lock_guard<mutex> lg(m_mutex);
if(sk.empty()) throw empty_stack();
T ret = sk.top();
tk.pop();
return ret;
}
bool empty(){
lock_guard<mutex> lg(m_mutex);
return sk.empty();
}
};
在链表的表头和表尾分别进行操作的时候可以用俩个互斥元来操作,这样可以提升并发的速率。
//相关代码有时间再补
原文:https://www.cnblogs.com/hebust-fengyu/p/12087827.html