環形緩衝區的c實現

2021-06-18 06:45:49 字數 2967 閱讀 2214

//標頭檔案

#ifndef __xbuf_h__

#define __xbuf_h__

#define xbufdefaultsize (1024*1024) //緩衝區預設大小

typedef unsigned int uint32;

//!建立乙個環形緩衝區 size為緩衝區大小

void *x_buf_create(uint32 size);

//!獲取緩衝區已有資料量的大小

uint32 x_buf_data_size(void *handle);

//!獲取緩衝區空閒空間的大小

uint32 x_buf_empty_size(void *handle);

//!緩衝區是否是滿的 0:否 1:是

uint32 x_buf_is_full(void *handle);

//!緩衝區是否是空的 0:否 1:是

uint32 x_buf_is_empty(void *handle);

//!將buf中的資料寫入緩衝區 返回實際寫入的資料量大小

uint32 x_buf_write(void *handle,char *buf,uint32 size);

//!讀取緩衝區的資料 返回實際讀取的資料量大小

uint32 x_buf_read(void *handle,char *buf,uint32 size);

//!將buf中的資料全部寫入緩衝區中 返回實際寫入的大小 返回值為0或者size

uint32 x_buf_write_block(void *handle,char *buf,uint32 size);

#endif //__xbuf_h__

#include "x_buf.h"

#include #include #include //環形緩衝區的結構體資訊

typedef struct xbufinfo

}x_buf_info;

//!建立乙個環形緩衝區 size為緩衝區大小

void *x_buf_create(uint32 size)

pbuf->buf = (char *)(pbuf+1);

//size即緩衝區的初始化大小<=0的話 用預設的值進行初始化

memset(pbuf->buf,0,size);

pbuf->bufsize = size;

pbuf->full = 0;

pbuf->head = 0;

pbuf->tail = 0;

return (void *)pbuf;

}//!獲取緩衝區已有資料量的大小

uint32 x_buf_data_size(void *handle)

assert(pbuf->bufsize);

return (pbuf->tail - pbuf->head + pbuf->bufsize)%pbuf->bufsize;

}//!獲取緩衝區空閒空間的大小

uint32 x_buf_empty_size(void *handle)

//!緩衝區是否是滿的 0:否 1:是

uint32 x_buf_is_full(void *handle)

//!緩衝區是否是空的 0:否 1:是

uint32 x_buf_is_empty(void *handle)

return 0;

}//!將buf中的資料寫入緩衝區 返回實際寫入的資料量大小

uint32 x_buf_write(void *handle,char *buf,uint32 size)

x_buf_info *pbuf = (x_buf_info *)handle;

/* 模型:

0 tail head bufsize - 1

| data | empty | data |

*/ if (pbuf->head > pbuf->tail)

/*模型:

0 head tail bufsize - 1

| empty | data | empty |

*/ else }

assert(pbuf->bufsize);

pbuf->tail = (pbuf->tail+size+pbuf->bufsize)%pbuf->bufsize;

if(pbuf->head == pbuf->tail)

return size;

}//!讀取緩衝區的資料 返回實際讀取的資料量大小

uint32 x_buf_read(void *handle,char *buf,uint32 size)

x_buf_info *pbuf = (x_buf_info *)handle;

/* 模型

0 head tail bufsize - 1

| empty | data | empty |

*/ if(pbuf->tail>pbuf->head)

/*模型

0 tail head bufsize - 1

| data | empty | data |

*/ else

//!將buf中的資料全部寫入緩衝區中 返回實際寫入的大小 返回值為0或者size

uint32 x_buf_write_block(void *handle,char *buf,uint32 size)

return x_buf_write(handle,buf,size);

}

c 環形緩衝區

public class circularbuffer icollection,ienumerable,icollection,ienumerable public circularbuffer int capacity,bool allowoverflow public bool allowove...

環形緩衝區的實現

乙個簡單的環形緩衝區,沒有寫加解鎖的部分,用於多執行緒的話還是自己加吧.pragma once include stdio.h include stdlib.h include memory.h namespace linker ring bool put elementtype e else bo...

環形緩衝區

include include include include include define buffsize 1024 1024 define min x,y x y x y pthread mutex t lock pthread mutex initializer struct cycle b...