支持多线程的FIFO实现
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <pthread.h>
#include "thread_safe_fifo.h"
#define MAX_BIT 8
#define MAX_SIZE (1<<MAX_BIT)
#define CH_SIZE 4
static struct s_fifo_node fifo_buff[CH_SIZE][ MAX_SIZE ] ;
static int wr_ptr[CH_SIZE]={0},rd_ptr[CH_SIZE]={0},gap[CH_SIZE]={0} ;
static int is_fifo_empty(int ch ){return ( gap[ch]==0 );}
static int is_fifo_full(int ch ){return ( gap[ch]==MAX_SIZE );}
static int get_fifo_gap(int ch ){return gap[ch];}
static void init_fifo(int ch){wr_ptr[ch] = rd_ptr[ch] = gap[ch] = 0;}
static int fifo_push(int ch,struct s_fifo_node *node ){
if (is_fifo_full (ch )) return 0;
fifo_buff[ch][wr_ptr[ch]] = *node ;
wr_ptr[ch]++;
wr_ptr[ch] &= ( MAX_SIZE - 1);
gap[ch]++;
return gap[ch];
}
struct s_fifo_node * fifo_pop(int ch ){
struct s_fifo_node * r ;
if (is_fifo_empty (ch)) return NULL;
r = &fifo_buff[ch][rd_ptr[ch]];
rd_ptr[ch]+=1;
rd_ptr[ch] &= ( MAX_SIZE - 1);
gap[ch]--;
return r;
}
//
static pthread_mutex_t fifo_mutex;
int my_fifo_init_safe(int ch ){
pthread_mutex_init( &fifo_mutex, NULL );
pthread_mutex_lock( &fifo_mutex );
init_fifo(ch );
pthread_mutex_unlock( &fifo_mutex );
}
int my_fifo_push_safe(int ch ,struct s_fifo_node *node ) {
pthread_mutex_lock( &fifo_mutex );
fifo_push(ch,node ) ;
pthread_mutex_unlock( &fifo_mutex );
}
struct s_fifo_node * my_fifo_pop_safe(int ch ) {
struct s_fifo_node * r ;
pthread_mutex_lock( &fifo_mutex );
r = fifo_pop( ch ) ;
pthread_mutex_unlock( &fifo_mutex );
}
int my_fifo_get_gap_safe (int ch ){
int r ;
pthread_mutex_lock( &fifo_mutex );
r = get_fifo_gap( ch );
pthread_mutex_unlock( &fifo_mutex );
return r ;
}
int my_fifo_if_empty_safe (int ch )
{
int r = my_fifo_get_gap_safe(ch);
return r==0;
}
int my_fifo_if_full_safe (int ch )
{
int r = my_fifo_get_gap_safe(ch);
return r == MAX_SIZE;
}
/ thread_safe_fifo.h
/*
#ifndef __THREAD_SAFE_FIFO_H
struct s_fifo_node{
int len ;
unsigned int buff [2048] ;
} ;
int init_fifo_safe() ;
int fifo_push_safe(struct s_fifo_node *node ) ;
struct s_fifo_node * (void);
int get_fifo_gap_safe (int ch );
#endif
*/
这是我用在多进程之间传输UDP数据包的FIFO,这里面很简单的实现是了一个数组循环队列,之后在调用的时候进行了加锁操作。在使用队里的数组的元素的时候没有进行加锁,这符合我程序要求,单是这个特征在你要reuse的时候一定注意论证一下。