高速缓冲区初始化

#include <stdio.h>
#include <stdlib.h>

#define BLOCK_SIZE      1024
#define BUFFER_SIZE     (1024*1024)    // 1M

static long NR_BUFFERS;


struct buffer_head
{
    int b_dev;
    int b_dirt;
    int b_count;
    int b_lock;
    int b_uptodate;
    int b_wait;
    struct buffer_head* b_next;
    struct buffer_head* b_prev;
    struct buffer_head* b_next_free;
    struct buffer_head* b_prev_free;
    char* b_data;
};

int main(void)
{
    void* buffer;
    struct buffer_head* start_bh;
    char* end_buffer;

    buffer = malloc(BUFFER_SIZE);
    if (NULL == buffer)
    {
        printf("allocated buffer error!\n");
        return -1;
    }

    start_bh = (struct buffer_head *)buffer;

    end_buffer = ((char *)start_bh) + BUFFER_SIZE;

    while ((void *)(end_buffer -= BLOCK_SIZE) >= ((void *)(start_bh+1)))
    {
        start_bh->b_dev = 0;
        start_bh->b_dirt = 0;
        start_bh->b_count = 0;
        start_bh->b_lock = 0;
        start_bh->b_uptodate = 0;
        start_bh->b_wait = 0;
        start_bh->b_next = NULL;
        start_bh->b_prev = NULL;
        start_bh->b_data = (char *)end_buffer;
        start_bh->b_prev_free = start_bh-1;
        start_bh->b_next_free = start_bh+1;
        start_bh++;
        NR_BUFFERS++;
    }

    free(buffer);

    printf("buffer block number[%d]\n", NR_BUFFERS);

    return 0;
}

/*
    output:
    buffer block number[981]
*/

主要技巧是分配一整块内存,前半部分存放数据结构的信息,后半部分存放数据信息,显然这里的两部分占用大小肯定不相当。

注意循环执行的条件,下一数据块的首地址不小于下一数据结构块尾地址加1,而且数据结构块是从低地址向高地址初始化的,而数据块的引用是高地址区向低地址区进行的。

posted @ 2013-07-07 22:32  WendellYih  阅读(360)  评论(0编辑  收藏  举报