码迷,mamicode.com
首页 > 其他好文 > 详细

环形无锁队列的简易实现

时间:2015-03-20 14:29:16      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

/*
 * RingBuf.h
 *
 *  Created on: Feb 7, 2015 6:06:10 PM
 *      Author: xuzewen
 */

#ifndef RINGBUF_H_
#define RINGBUF_H_

#include <libmisc.h>

/**
 *
 * 多/单线程生产, 只能单线程消费, 尺寸固定为0x10000.
 *
 * */
class RingBuf
{
public:
	ushort ccur; /** 消费游标. */
	uint pcur; /** 生产游标. */
	size_t* ring;
public:
	RingBuf();
	virtual ~RingBuf();
public:
	bool push(void* e); /** 添加, 反复尝试, 直到成功为止. */
	void* pop(); /** 弾出, 总是立即返回, 无元素时返回空. */
	int size(); /** 返回元素个数. */
};

#endif /* RINGBUF_H_ */


实现:

/*
 * RingBuf.cpp
 *
 *  Created on: Feb 7, 2015 6:06:10 PM
 *      Author: xuzewen
 */

#include "RingBuf.h"

RingBuf::RingBuf()
{
	this->pcur = 0;
	this->ccur = 0;
	this->ring = (size_t*) calloc(1, sizeof(size_t) * 0x10000);
}

/** 添加, 反复尝试, 直到成功为止. */
bool RingBuf::push(void* f)
{
	while (!__sync_bool_compare_and_swap(this->ring + (this->pcur & 0x0000FFFF), 0, (size_t) f))
		usleep(1000);
	//__sync_fetch_and_add(&this->pcur, 1);	/** 多线程生产者. */
	//
	++this->pcur; /** 单线程的生产者. */
	return true;
}

/** 弾出, 总是立即返回, 无元素时返回空. */
void* RingBuf::pop()
{
	if (this->ring[this->ccur] == 0)
		return NULL;
	void* r = (void*) this->ring[this->ccur];
	this->ring[this->ccur] = 0;
	++this->ccur;
	return r;
}

int RingBuf::size()
{
	int size = 0;
	for (int i = 0; i < 0x10000; ++i)
	{
		if (this->ring[this->ccur] != 0)
			++size;
	}
	return size;
}

RingBuf::~RingBuf()
{

}


测试:

/*
 * main.cpp
 *
 *  Created on: Mar 20, 2015 12:09:33 PM
 *      Author: xuzewen
 */

#include "RingBuf.h"

static RingBuf* r = new RingBuf();

void svc()
{
	ullong last = 0;
	ullong ts = 0;
	while (1)
	{
		ullong c = (ullong) r->pop();
		if (c == 0) /** not NULL. */
		{
			usleep(100);
			continue;
		}
		if (c - last != 1)
		{
			printf("it`s a bug, c: %llu, last: %llu\n", c, last);
			exit(1);
		}
		last = c;
		if ((c % 20000000) == 0)
		{
			ullong now = Misc::getDiDa(); /** 系统嘀嗒声. */
			printf("ts: %llu, last: %llu\n", now - ts, last);
			ts = now;
		}
	}
}

int main(int argc, char **argv)
{
	Misc::newThread(svc); /** 单线程消费. */
	//
	for (ullong c = 1;; ++c) /** 单线程生产. */
		r->push((void*) c); /** 按顺序push. */
	return EXIT_SUCCESS;
}


测试结果:

技术分享


按每2000万条消息, 消耗470毫秒算, 并发数为4255万条/秒. 单线程生产, 单线程消费, 两个线程接近跑满.





环形无锁队列的简易实现

标签:

原文地址:http://blog.csdn.net/xzwdev/article/details/44490139

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!