/*
使用锁第线性安全链表:
功能如下:
1、项链表添加新项目;
2、从链表中删除满足一定条件的项目;
3.在链表中查找满足一定条件的项目;
4,更新满足一定条件的项目;
4.复制链表中每个项目到两一个容器中;
*/
#include<mutex>
#include<memory>
#include<iostream>
template<typename T>
class threadsafe_list
{
struct node
{
std::shared_ptr<T> data;
std::unique_ptr<node> next;
std::mutex m;
node() :next()
{}
node(T const& value) :data(make_shared<T>(value))
};
node head;
threadsafe_list(){}
~threadsafe_list()
{
remove_if([](node const&){return true; });
}
threadsafe_list(threadsfe_list const& other) = delete;
threadsafe_list& operator=(threadsfe_list const& other) = delete;
void push_front(T const& value)
{
std::unique_ptr<node>new_node(new node(value));
std::lock_guard<std::mutex> lk(head.m)
new_node->next = std::move(head.next);
head.next = std::move(new_node);
}
template<typename Function>
void for_each(Function f)
{
node current = &head;
std::unique_lock<std::mutex> lk(head.m);
while (node* const next = current->next.get())
{
std::unique_lock<std::mutex>next_lk(next->m);
lk.unlock();
f(*next->data);
current = next;
lk = std::move(next_lk);
}
}
template<typename Predicate>
std::shared_ptr<T>find_first_if(Predicate p)
{
node* current = &head;
std::unique_lock<std::mutex>lk(head.m);
while (node *const next = current->next.get())
{
std::unique_lock<std::mutex> next_lk(next->m);
lk.unlock();
if (p(*next->data))
{
return next->data;
}
current = next;
lk = std::move(next_lk);
}
return std::shared_ptr<T>();
}
template<typename Predicate>
viod remove_if(Predicate p)
{
node* current = &head;
std::unique_lock<std::mutex>lk(head.m);
while (node* const next = current->next.get())
{
std::unique_lock<std::mutex>next_lk(next->m);
if (p(*next->data))
{
std::unique_ptr<node> old_next = std::move(current->next);
current->next = std::move(next->next);
next_lk.unlock();
}
else {
lk.unlock();
current = next;
lk = std::move(next_lk);
}
}
}
};
使用锁的线性安全链表
最新推荐文章于 2023-05-13 13:27:03 发布