看到一些大牛关于无锁双向链表的实现方式,自己尝试着写一个,但是实现起来有问题,还没有完成对应的功能。先在这里贴出来,有兴趣的可以一起讨论。
//实现无锁双向可删除队列
// 头入队,尾出队,中间可以删除
#define DELETED -1
struct Node{
Node * xor;
Node * pre;
Node * next;
long data;
};
struct Queen{
Node *head;
Node *tail;
Node *begin;
Node *end;
};
void InitQueen(Queen * q)
{
//q->head= (Node*)&q->tail;//保持前置和后继七点的xor值,因为是头节点,只保存后继节点的地址
//q->tail= (Node*)&q->head;//保持前置和后继七点的xor值,因为是尾节点,只保存前置节点的地址
q->begin = (Node*)malloc(sizeof(Node));
q->end = (Node*)malloc(sizeof(Node));
q->begin->next = q->end;
q->begin->pre = 0;
q->begin->xor = (Node*)((long)q->begin->next^(long)q->begin->pre);
q->end->pre = q->begin;
q->end->next = 0;
q->end->xor = (Node*)((long)q->end->pre^(long)q->end->next);
q->head = q->begin;
q->tail = q->end;
};
Node * EnterQueen(Queen * q,Node * n)
{
LONGLONG llp= (LONGLONG)(q->end);
llp = (llp<<32)|(LONG)(q->begin);
Node *h = q->head;
Node *b = q->begin;
Node *e = q->end;
Node *t = q->tail;
n->pre = h;
n->next = h->next;
n->xor = (Node*)((long)n->pre^(long)n->next);
LONGLONG ll= (LONGLONG)n;
ll = (ll<<32)|ll;
if (llp==InterlockedCompareExchange64((LONGLONG*)q,ll,llp))
return n;
Node ** ph;
do
{
ph = &q->head;
h = q->head;
//n->pre = q->begin;
//n->next = q->head;
n->xor = (Node*)((long)q->begin^(long)q->head);
q->begin->xor = n;
}
while ((long)h != InterlockedCompareExchange((long*)ph,(long)n,(long)q->head));
return n;
}
Node * ExitQueen(Queen * q)
{
Node * h = q->tail;
Node * nh = (Node*)((long)q->end^(long)q->tail->xor);
h->xor = nh;
h->next = 0;
q->end = h;
q->tail = nh;
return h;
}
int DeleteNode(Queen * q,long data)
{
return 0;
}
void TravelQueen(Queen * q)
{
Node *h = q->head;
Node *b = q->begin;
Node *e = q->end;
Node *t = q->tail;
Node *p = q->begin;
Node *c = q->head;
Node *k;
printf("\n");
while(c!=q->tail)
{
//printf("pre:%d\t next:%d\t data:%d\t xor:%d \n",c->pre,c->next,c->data,c->xor);
printf("p:%d\t,c:%d\t,data:%d\t xor:%d \n",p,c,c->data,c->xor);
k = c;
c = (Node*)((long)p^(long)c->xor);
p = k;
}
//printf("pre:%d\t next:%d\t data:%d\t xor:%d \n",c->pre,c->next,c->data,c->xor);
printf("p:%d\t,c:%d\t,data:%d\t xor:%d \n",p,c,c->data,c->xor);
}
int main()
{
Queen q;
InitQueen(&q);
for (int i = 0;i<20;++i)
{
Node * n = (Node*)malloc(sizeof(Node));
n->data = i*5;
n->xor = 0;
EnterQueen(&q,n);
TravelQueen(&q);
}
for (int j = 0;j<10;++j)
{
Node * n = ExitQueen(&q);
if (n)
{
free(n);
}
TravelQueen(&q);
}
0;
}