redis源码分析(一)

今日起,结合已经看过的所有的redis的命令以及高级属性,做redis的源码级别的分析。
redis-2.8-7
先说 list集合,主要两个文件adlist.c 以及adlist.h

这个和java中定义的list区别不大,就是自己实现了一遍
adlist.c

/* Add a new node to the list, to head, contaning the specified 'value'
* pointer as value.
*
* On error, NULL is returned and no operation is performed (i.e. the
* list remains unaltered).
* On success the 'list' pointer you pass to the function is returned. */
list *listAddNodeHead(list *list, void *value)
{
listNode *node;

if ((node = zmalloc(sizeof(*node))) == NULL)
return NULL;
node->value = value;
if (list->len == 0) {
list->head = list->tail = node;
node->prev = node->next = NULL;
} else {
node->prev = NULL;
node->next = list->head;
list->head->prev = node;
list->head = node;
}
list->len++;
return list;
}

还是看功能吧(代码看不懂回去看数据结构去,第二章就是),此处不多说了。

/* Create a new list. The created list can be freed with
* AlFreeList(), but private value of every node need to be freed
* by the user before to call AlFreeList().
*
* On error, NULL is returned. Otherwise the pointer to the new list. */
list *listCreate(void)
{
struct list *list;

if ((list = zmalloc(sizeof(*list))) == NULL)
return NULL;
list->head = list->tail = NULL;
list->len = 0;
list->dup = NULL;
list->free = NULL;
list->match = NULL;
return list;
}

创建一个新的链表时候,注意里面申请内存分配的时候用到的一个函数 zmalloc(),这个需要仔细分析下的
以及下面用到的一个函数


/* Free the whole list.
*
* This function can't fail. */
void listRelease(list *list)
{
unsigned long len;
listNode *current, *next;

current = list->head;
len = list->len;
while(len--) {
next = current->next;
if (list->free) list->free(current->value);
zfree(current);
current = next;
}
zfree(list);
}

zfree()函数,redis封装的内存释放的函数。

zmalloc()与 zfree()函数 都在 zmalloc.c 与zmalloc.h中定义

自定义的redis内存控制完成了如下功能:
如果系统有GOOGLE的TC_MALLOC库,则采用TC_MALLOC代替原有的MALLOC系列函数
如果是MAC系统,使用malloc.h中的内存分配函数
以上两种情况均不使用redis的内存分配函数,其余的情况下使用。
其他,在每一段分配好的存储空间前头,再加一个定长的字段,记录所分配的空间大小

同时在查阅这两个函数的时候发现有zmalloc_get_rss函数,该函数就是读取的操作系统内存使用情况。

代码中  HAVE_MALLOC_SIZE 是用来确定系统中是否有MALLOC函数的。
redis的内存分配在数据量比较大的时候很有效。如果只想malloc请求分配一个byte的内存空间,但redis处于内存对齐(原因:1. 不是所有的硬件平台都能访问任意地址上的任意数据的;某些硬件平台只能在某些地址处取某些特定类型的数据,否则抛出硬件异常;2.数据结构 (尤其是栈)应该尽可能地在自然边界上对齐。原因在于,为了访问未对齐的内存,处理器需要作两次内存访问;而对齐的内存访问仅需要一次访问 )的考虑,可能会分配4个byte的内存空间,这样,如果大量请求的话,会有很多内存得不到有效利用,造成大量内存碎片。

但是我们很少是这么小的字节,可以先不考虑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值