无锁队列的原理与实现

近期几天在思考无锁队列。看了相关文章,也读了一些博客,最后写了一份代码,代码实现对在多线程环境下对队列的读和写是不须要加锁的。

代码例如以下所看到的:


#include <windows.h>
#pragma comment(lib, "Kernel32.lib")

template<typename VT>
class LcFQue{//lock free queue
public:
	struct QueNode{
		QueNode *next;
		VT 		value;
	};
public:
	LcFQue();
	~LcFQue();
public:
	void	EnQue(const VT& val);
	VT		DeQue();
private:
	QueNode	*tail;
	QueNode	*head;
};

template<typename VT>
LcFQue<VT>::LcFQue(){
	tail= head= new QueNode;
	tail->value= -1;
	tail->next= NULL;
}

template<typename VT>
LcFQue<VT>::~LcFQue(){
	QueNode* DelNode= head;
	while(DelNode!= tail){
		head= head->next;
		delete DelNode;
		DelNode= head;
	}
	delete DelNode;
}

template<typename VT>
void LcFQue<VT>::EnQue(const VT& val){
	QueNode* node	= new QueNode;
	node->next		= NULL;
	node->value		= val;
	QueNode* tTail;
	do{
		tTail= tail;
	}while(InterlockedCompareExchange((LONG*)&(tTail->next),(LONG)node,NULL)!= NULL);
	InterlockedCompareExchange((LONG*)(&tail),(LONG)node,(LONG)tTail);
}

template<typename VT>
VT LcFQue<VT>::DeQue(){
	QueNode* tHead;
	do{
		tHead= head;
		if(tHead->next==NULL){
			return -1;
		}
	}while(InterlockedCompareExchange((LONG*)(&head),(LONG)(head->next),(LONG)tHead)!= (LONG)tHead);
	return tHead->next->value;
}

#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
LcFQue<int> que;


int C[1000];
DWORD WINAPI  EnQue(void* ParAddr);
DWORD WINAPI  Deque(void* ParAddr);
int main(){
	memset(C,0,sizeof(C));
	srand(time(NULL));
	HANDLE hThread[10];
	int AddEd[10];
	for(int i= 0; i< 10; ++i){
		AddEd[i]= i;
	}
	LPTHREAD_START_ROUTINE func;
	for(int i= 0; i< 10; ++i){
		if(i> 5){
			func= Deque;
		}else{
			func= EnQue;
		}
		hThread[i]= ::CreateThread(
			NULL,
			0,
			func,
			AddEd+i,
			0,
			NULL
			);
	}
	::WaitForMultipleObjects(10,hThread,TRUE,INFINITE);
}

DWORD WINAPI Deque(void* ParAddr){
	while(true){
		::Sleep(10);
		int val= que.DeQue();
		if(val==-1){
			continue;
		}
		cout<<val<<'\n';
		++C[val];
	}
	return 0;
}

DWORD WINAPI  EnQue(void* ParAddr){
	int* obj= (int*)ParAddr;
	for(int i= 0; i< 100; ++i){
		que.EnQue(i*5+*obj);
		::Sleep(rand()%10);
	}
	return 0;
}


转载于:https://www.cnblogs.com/zhchoutai/p/6735973.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值