Multithreading c+中的区域协调单位+;11使用std::shared_ptr和更多?
下面是我为解决服务器上的问题而编写的一些代码。 这有效吗? 我已经测试过了,它是有效的,但我想听听大家的意见。谢谢 所以基本上它是一个基于RCU概念的单锁自由链接列表Multithreading c+中的区域协调单位+;11使用std::shared_ptr和更多?,multithreading,c++11,concurrency,parallel-processing,Multithreading,C++11,Concurrency,Parallel Processing,下面是我为解决服务器上的问题而编写的一些代码。 这有效吗? 我已经测试过了,它是有效的,但我想听听大家的意见。谢谢 所以基本上它是一个基于RCU概念的单锁自由链接列表 class data_list { CRITICAL_SECTION update; std::atomic_int64_t count; concurrency::concurrent_queue<std::shared_ptr<data>> to_add; concurr
class data_list
{
CRITICAL_SECTION update;
std::atomic_int64_t count;
concurrency::concurrent_queue<std::shared_ptr<data>> to_add;
concurrency::concurrent_queue<int> to_remove;
public:
data_list() :head(nullptr), count(0) { InitializeCriticalSection(&update); }
~data_list() {
DeleteCriticalSection(&update);
std::shared_ptr<node> cursor = head;
head = nullptr;
while (1)
{
if (!cursor) break;
cursor = cursor->next;
}
}
struct node { std::shared_ptr<data> d; std::shared_ptr<node> next; };
std::shared_ptr<node> head;
…没有意见?我发现了一个bug…谢谢你的帮助>>你应该在codereview.stackexchange.com/wow上发布,我不知道这个!谢谢
int push_front(std::shared_ptr<data> d)
{
to_add.push(std::move(d));
if (!TryEnterCriticalSection(&update))
return 0;
int a = 0;
while (1)
{
if (!to_add.try_pop(d)) break;
std::shared_ptr<node> temp = std::make_shared<node>();
temp->d = d;
temp->next = head;
while (1) { if (std::atomic_compare_exchange_weak(&head, &head, temp)) break; }
a++;
count++;
}
LeaveCriticalSection(&update);
return a;
}
void remove(int uid)
{
to_remove.push(uid);
if (!TryEnterCriticalSection(&update))
return;
std::shared_ptr<node> back;
std::shared_ptr<node> front;
while (1)
{
if (!to_remove.try_pop(uid)) break;
back = nullptr;
front = head;
while (1)
{
if (!front) break;
if (front->d->uid == uid) {
if (back)
{
back->next = front->next;
while (1) { if (std::atomic_compare_exchange_weak(&back->next, &back->next, front->next))break; }
}
else
{
while (1) { if (std::atomic_compare_exchange_weak(&head, &head, front->next))break; }
}
count--;
break;
}
back = front;
front = front->next;
}
}
LeaveCriticalSection(&update);
}
std::shared_ptr<data> get(int uid) const
{
std::shared_ptr<node> temp = std::atomic_load(&head);
while (1)
{
if (!temp)break;
if (temp->d->uid == uid)
return temp->d;
temp = std::atomic_load(&temp->next);
}
return nullptr;
}
void collect(int v, std::vector<std::shared_ptr<data>> & out_collection) const
{
std::shared_ptr<node> temp = std::atomic_load(&head);
while (1)
{
if (!temp)break;
if (temp->d->b == v)
out_collection.push_back(temp->d);
temp = std::atomic_load(&temp->next);
}
}
int64_t get_count() const
{
return count.load(std::memory_order_relaxed);
}
};