cc++ 消息队列(循环数组实现)

cc++ 消息队列(循环数组实现),第1张

c/c++ 消息队列(循环数组实现)

         --未设置访问控制,多线程或者多进程使用需要加互斥锁保护。

typedef struct _tagFIFO_QUE {
    void* cycleQue;//队列的起始地址
    long long front;//队列的头偏移
    long long rear;//队列的尾偏移
    unsigned long dataSize;//元素的大小
    unsigned long maxLen;//元素的个数*元素的大小
}FIFO_QUE, *LPFIFO_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;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5651436.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存