linux c queue 队列的实现

linux c queue 队列的实现
https://www.zentut.com/c-tutorial/c-queue/

问题1

把一个 struct msg_event 放入queue ,
queue会自动复制一份 msg_event吗?
然后将复制的内容传给 get_queue的地方.

这样 就可以将 函数中的 临时变量 put_queue()
然后临时变量 被释放了,也不影响.

问题2

制作一个线程安全的 queue.

有人 是在 queue中使用了 malloc,如果提前分配好内存,比如数组?

1111

问题3

如何在 里面加入
pthread_mutex_lock
pthread_cond_wait
pthread_cond_signal
pthread_mutex_unlock

没有数据的时候等待
等数据到来的时候,发送一个信号量.

数据结构之循环队列c语言实现

https://blog.51cto.com/u_12138867/1869846

#include <stdio.h>
#include <stdlib.h>

/* 循环队列大小*/
#define MAX 8     

typedef struct queue {
	int *que_array;
	int front;		//指向队首
	int rear;		//指向队尾
	int valid_cnt;	//队列中有效的数据个数
    int total;      //队列总大小
} queue_t;

typedef enum {
    E_NONE     = 0,
    E_NOMEMORY = 1,
    E_FAIL     = 2,
} error_t;

void init_queue(queue_t *que)
{
	que->que_array = (int *)malloc(sizeof(int) * MAX);
	if (que->que_array == NULL) {
		printf("no mem\n");
		exit(-E_NOMEMORY);
	}
	que->front     = 0;
    que->rear      = 0;
	que->valid_cnt = 0;
    que->total     = MAX;
}

/* 判断队列是否已满 */
int is_full(queue_t *que)
{
	return (((que->rear + 1) % que->total) == (que->front));
}

/* 判断队列是否为空 */
int is_empty(queue_t *que)
{
	return (que->front == que->rear);
}

/* 元素入队 */
void entry_queue(queue_t *que, int data)
{
	if (is_full(que)) {
		printf("队列已满,添加后有可能会覆盖掉前面的元素 \n");
		que->front = ((que->front+1) % que->total);
	}
	que->que_array[que->rear % que->total] = data;
	que->rear = (que->rear+1) % que->total;
	que->valid_cnt++;
}

/* 元素出队 */
int del_queue(queue_t *que)
{
    int tmp;
    
    if (is_empty(que)) {
        printf("队列为空 \n");
        return -E_FAIL;
    }
    
    tmp = que->que_array[que->front % que->total];
	que->front = ((que->front+1) % que->total);
	que->valid_cnt--;
    
    return tmp;
}

int main(int argc, char *argv[])
{
    int tem_data,i;
	queue_t que;
    
	init_queue(&que);

#if 0
	for (i = 0; i < 7; i++) {
		entry_queue(&que, i + 1);
	}

    printf("出队队列中的所有元素 \n");
	while (!is_empty(&que)) {
		printf("%d,", del_queue(&que));
	}
#endif
	
    /*接下来,添加十个元素试试*/
    for (i = 0; i < 10; i++) {
		entry_queue(&que, i + 1);
	}

    printf("出队队列中的所有元素 \n");
	while (!is_empty(&que)) {
		printf("%d,", del_queue(&que));
	}
    
	return 0;
}
Linux内核中的循环队列

http://www.rcstech.org/linux-kfifo
本文介绍linux内核中一个实现十分巧妙的数据结构:无锁循环队列kfifo。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值