一个简单的循环队列
前言
有个需求,要求一个客户端不断地接收数据与发送数据,特别是发送数据,既要求接收数据后立即发送,还要求该数据在经过一段时间后再发送一遍。因此决定使用一个循环队列来实现
实现
结构实现
#include <stdio.h>
#include <string.h>
#define BUF_SIZE 1000
#define DATA_LEN 256
typedef struct
{
char buf[BUF_SIZE][DATA_LEN]; // 数据域
unsigned int readpos; // 延时读指针
unsigned int writepos; // 延时写指针
unsigned int rtreadpos; // 实时读指针
unsigned int rtwritepos; // 实时写指针
} queue;
// 向循环队列中写入数据
void write_data(queue *m_queue, char *data, int data_len)
{
if (data_len <= 0)
{
printf("No data to write\n");
return;
}
// 加锁
unsigned int wpos = m_queue->writepos;
memcpy(m_queue->buf[wpos], data, data_len);
// 写完数据后,要移动写指针
m_queue->writepos = (m_queue->writepos + 1 + BUF_SIZE) % BUF_SIZE;
m_queue->rtwritepos = (m_queue->rtwritepos + 1 + BUF_SIZE) % BUF_SIZE;
// 解锁
return;
}
void read_pos(queue *m_queue, int delay)
{
// 上锁
unsigned int j = 0;
unsigned int rtpos = m_queue->rtreadpos;
unsigned int dpos = m_queue->readpos;
unsigned int datalen;
if (delay == 0)
{
j = 0;
if (m_queue->rtreadpos == m_queue->rtwritepos)
{
return;
}
rtpos = m_queue->rtreadpos;
datalen = (m_queue->rtwritepos - m_queue->rtreadpos + BUF_SIZE) % BUF_SIZE;
while (j < datalen)
{
rtpos = (j + m_queue->rtreadpos) % BUF_SIZE;
// 这里发送数据
j++;
}
// 说明是实时发送
}
else
{
// 延时发送
dpos = m_queue->readpos;
datalen = (m_queue->writepos - m_queue->readpos + BUF_SIZE) % BUF_SIZE;
while (j < datalen)
{
// 延时发送还需要判断延时时间
// 这里不再加这一层判断
dpos = (j + m_queue->readpos) % BUF_SIZE;
// 发送数据
j++;
}
}
// 这里要更新两个读指针的位置
if (m_queue->rtreadpos != rtpos)
{
m_queue->rtreadpos = (rtpos + 1 + BUF_SIZE) % BUF_SIZE;
}
if (m_queue->readpos != dpos)
{
m_queue->readpos = (dpos + 1 + BUF_SIZE) % BUF_SIZE;
}
// 解锁
return;
}
评论
0 评论