在glib里面一般都有一套现成的可以用的队列,链表函数可以用,mplayer,ffmpeg等开源软件里面也有相应的实现,我们在写程序时也经常要用到这样的功能,可以借鉴里面的实现方法,实现自己的库函数,减少程序的依赖性。下面是我常用的自己的库,大多是借鉴mplayer里面的思路.
/*packet_queue.h*/
#ifndef _PACKET_QUEUE_H_
#define _PACKET_QUEUE_H_
#include
typedef struct packet_stream_st{
int len;
unsigned char *buffer;
struct packet_stream_st *next;
}packet_stream_t;
typedef struct {
int packs;
packet_stream_t *first;
packet_stream_t *last;
}queue_stream_t;
packet_stream_t* new_packet_stream(int len);
void free_packet_stream(packet_stream_t* ps);
queue_stream_t* new_queue_stream();
void free_queue_stream(queue_stream_t* qs);
void qs_add_packet(queue_stream_t* qs, packet_stream_t* ps);
packet_stream_t* qs_get_packet(queue_stream_t* qs);
#endif
/*packet_queue.c*/
#include
#include "packet_queue.h"
packet_stream_t* new_packet_stream(int len)
{
packet_stream_t* ps = (packet_stream_t*)malloc(sizeof(packet_stream_t));
ps->next = NULL;
ps->buffer = (unsigned char *)malloc(len);
ps->len = len;
return ps;
}
void free_packet_stream(packet_stream_t* ps)
{
if(ps){
if(ps->buffer) {free(ps->buffer); ps->buffer=NULL;}
free(ps);
ps = NULL;
}
}
queue_stream_t* new_queue_stream()
{
queue_stream_t *qs = (queue_stream_t*)malloc(sizeof(queue_stream_t));
qs->packs = 0;
qs->first = qs->last = NULL;
return qs;
}
static void qs_free_packs(queue_stream_t* qs)
{
packet_stream_t* ps = qs->first;
while(ps){
packet_stream_t* pn = ps->next;
free_packet_stream(ps);
ps = pn;
}
qs->packs = 0;
qs->first = qs->last = NULL;
}
void free_queue_stream(queue_stream_t* qs)
{
qs_free_packs(qs);
free(qs);
}
void qs_add_packet(queue_stream_t* qs, packet_stream_t* ps)
{
++qs->packs;
if(qs->last){
qs->last->next = ps;
qs->last = ps;
}else{
qs->first = qs->last = ps;
}
}
packet_stream_t* qs_get_packet(queue_stream_t* qs)
{
if(qs->packs){
packet_stream_t* ps = qs->first;
qs->first = ps->next;
if(!qs->first) qs->last = NULL;
--qs->packs;
return ps;
}
return NULL;
}
/*usage: main.c*/
#include
#include
#include "packet_queue.h"
int main()
{
int i;
queue_stream_t * qs = new_queue_stream();
for(i=0; i<10; i++){
packet_stream_t *ps = new_packet_stream(32);
strcpy(ps->buffer,"Hello World!");
printf("===current adding queue len:%d=====\n",qs->packs);
qs_add_packet(qs, ps);
}
for(i=0; i<20; i++){
packet_stream_t *ps = qs_get_packet(qs);
if(ps){
printf("===current reading queue len:%d=====\n",qs->packs);
printf("packet:%s\n",ps->buffer);
}
}
free_queue_stream(qs);
return 0;
}
/*Makefile*/
TARGET=test_queue
CROSS_COMPILE =
CC = $(CROSS_COMPILE)gcc
LD = $(CROSS_COMPILE)ld
STRIP = $(CROSS_COMPILE)strip
SRC=${wildcard *.c lib/*.c}
OBJS=${SRC:%.c=%.o}
NAME=${SRC:%.c=%}
DEPS=$(SRC:%.c=.dep/%.d)
CFLAGS= -g -Wall -Iinclude -Llib
LDFLAGS=
.PHONY: dep all
all : $(OBJS)
$(CC) -o $(TARGET) $(OBJS) $(LDFLAGS)
%.o: %.c
${CC} ${CFLAGS} -c $< -o $@
clean:
rm -rf .dep .tmp .src.mk $(TARGET) $(OBJS)
阅读(1030) | 评论(0) | 转发(0) |