環形雙緩衝佇列
原文來自,已經做修改,在VS2015上測試沒問題
// ConsoleApplication1.cpp : 定義控制檯應用程式的入口點。
//#include "stdafx.h"
#include"string.h"
#include"stdio.h"
#include <stdlib.h>
#define BUFFSIZE 255
#define min(x, y) ((x) < (y) ? (x) : (y))
struct cycle_buffer {
unsigned char *buf;
unsigned int size;
unsigned int in;
unsigned int out;
};
static struct cycle_buffer *fifo = NULL;
static int init_cycle_buffer(void)
{
int size = BUFFSIZE, ret;
ret = size & (size - 1);//按位與50->51
if (!ret)
return ret;
fifo = (struct cycle_buffer *) malloc(sizeof(struct cycle_buffer));
if (!fifo)
return -1;
memset(fifo, 0, sizeof(struct cycle_buffer));
fifo->size = size;
fifo->in = fifo->out = 0;
fifo->buf = (unsigned char *)malloc(size);
if (!fifo->buf)
free(fifo);
else
memset(fifo->buf, 0, size);//初始化fifo
return 0;
}
unsigned int fifo_get(unsigned char *buf, unsigned int len)
{
unsigned int l;
len = min(len, fifo->in - fifo->out);
l = min(len, fifo->size - (fifo->out & (fifo->size - 1)));
memcpy(buf, fifo->buf + (fifo->out & (fifo->size - 1)), l);
memcpy(buf + l, fifo->buf, len - l);
fifo->out += len;
return len;
}
unsigned int fifo_put(unsigned char *buf, unsigned int len)
{
unsigned int l;
len = min(len, fifo->size - fifo->in + fifo->out);
l = min(len, fifo->size - (fifo->in & (fifo->size - 1)));
memcpy(fifo->buf + (fifo->in & (fifo->size - 1)), buf, l);
memcpy(fifo->buf, buf + l, len - l);
fifo->in += len;
return len;
}
static void thread_read(void)
{
unsigned char buf[16];
unsigned int n;
memset(buf, 0, sizeof(buf));
n = fifo_get(buf, sizeof(buf));
printf("nnafter thread_read : %s %d \n ", buf, sizeof(buf));
}
static void thread_write(void)
{
unsigned char buf[] = "hello world";
fifo_put(buf, sizeof(buf));
}
int main(void)
{
int ret;
ret = init_cycle_buffer();
if (ret == -1)
return ret;
printf("start run\n");
thread_write();
thread_read();
while (1);
return 0;
}