概述
--未设置访问控制,多线程或者多进程使用需要加互斥锁保护。
typedef struct _tagFIFO_QUE {
void* cycleQue;//队列的起始地址
long long front;//队列的头偏移
long long rear;//队列的尾偏移
unsigned long maxLen;//元素的最大数量*元素的大小,也就是cycleQue指针指向的内存空间大小
}FIFO_QUE, *LPFIFO_QUE;
LPFIFO_QUE CreateCycleQue(unsigned long size)
{
LPFIFO_QUE que = (LPFIFO_QUE)malloc(sizeof(FIFO_QUE));
if(que==NULL)
return NULL;
que->front = 0;
que->rear = 0;
que->maxLen = size + 1;
que->cycleQue = malloc(que->maxLen);
if(que->cycleQue==NULL)
{
free(que);
return NULL;
}
return que;
}
void DestoryCycleQue(LPFIFO_QUE que)
{
if(que->cycleQue!=NULL)
{
free(que->cycleQue);
}
free(que);
}
bool IsQueEmpty(LPFIFO_QUE que) {
if (que->front == que->rear) {
return true;
}
else
return false;
}
bool IsQueFull(LPFIFO_QUE que) {
if ((que->rear + 1)%que->maxLen == que->front) {
return true;
}
else
return false;
}
unsigned long GetWritableSize(LPFIFO_QUE que) {
if (que->rear - que->front >= 0) {
return que->maxLen - (que->rear - que->front) - 1;
}
else {
return que->front - que->rear - 1;
}
}
bool EnQue(LPFIFO_QUE que, void* msg, DWORD msg_size) {
if (IsQueFull(que))
return false;
if (GetWritableSize(que) < msg_size) {
return false;
}
if (que->rear + msg_size > que->maxLen) {
long long part1 = msg_size - (que->rear + msg_size) % que->maxLen;
memcpy((char*)que->cycleQue + que->rear, msg, part1);
que->rear = (que->rear + part1) % que->maxLen;
memcpy((char*)que->cycleQue + que->rear, (char*)msg+part1, msg_size-part1);
que->rear = (que->rear + msg_size - part1) % que->maxLen;
}
else {
memcpy((char*)que->cycleQue+que->rear, msg, msg_size);
que->rear = (que->rear + msg_size) % que->maxLen;
}
return true;
}
unsigned long GetReadableSize(LPFIFO_QUE que) {
if (que->rear - que->front >= 0)
return (unsigned long)(que->rear - que->front);
else
return que->maxLen + que->rear - que->front;
}
bool DeQue(LPFIFO_QUE que, void* plane, unsigned long size) {
if (IsQueEmpty(que))
return false;
if (GetReadableSize(que) < size)
return false;
if (que->front + size < que->maxLen) {
memcpy((char*)plane, (char*)que->cycleQue + que->front, size);
que->front = (que->front + size) % que->maxLen;
}
else {
long long part1 = size - (que->front + size) % que->maxLen;
memcpy((char*)plane, (char*)que->cycleQue + que->front, part1);
que->front = (que->front + part1)% que->maxLen;
memcpy((char*)plane+ part1, (char*)que->cycleQue + que->front, size-part1);
que->front = (que->front + size - part1) % que->maxLen;
}
return true;
}
最后
以上就是健康母鸡为你收集整理的c/c++ 消息队列(循环数组实现)的全部内容,希望文章能够帮你解决c/c++ 消息队列(循环数组实现)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复