支持多线程的FIFO实现

66 篇文章 22 订阅
28 篇文章 11 订阅

支持多线程的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的时候一定注意论证一下。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值