双向无锁链表(未完成)

看到一些大牛关于无锁双向链表的实现方式,自己尝试着写一个,但是实现起来有问题,还没有完成对应的功能。先在这里贴出来,有兴趣的可以一起讨论。

//实现无锁双向可删除队列
// 头入队,尾出队,中间可以删除

#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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值