C语言 FIFO(宏)
本文地址:http://tongxinmao.com/Article/Detail/id/112
#if !defined(_MESSAGEOBJECT_H_)
#define _MESSAGEOBJECT_H_
#define START_CRITICAL() EA=0
#define END_CRITICAL() EA=1
/***********************************************************************\
Basic Thread/Interrupt Safe Queue Mechanism
\***********************************************************************/
/* 声明FIFO */
#define DECLARE_MSG_QUEUE(NAME,TYPE,SIZE)\
xdata struct\
{\
int ri;\
int wi;\
int max;\
##TYPE buffer[SIZE];\
} ##NAME;
/* 初始化消息队列 */
#define MSG_INITQUEUE(NAME,SIZE)\
{\
##NAME.ri = ##NAME.wi = 0;\
##NAME.max = SIZE;\
}
/* 向FIFO加入一个消息 */
// Prototype: void MSG_ENQUEUE(char *NAME, UCHAR C)
#define MSG_ENQUEUE(NAME,C)\
{\
START_CRITICAL();\
##NAME.buffer[##NAME.wi] = C;\
##NAME.wi++;\
if(##NAME.wi == ##NAME.max) ##NAME.wi=0;\
END_CRITICAL();\
}
/* 向FIFO加入一个串消息 */
// Prototype: void MSG_ENQUEUESTR(char *NAME, UCHAR* S, int LEN)
#define MSG_ENQUEUESTR(NAME,S,LEN)\
{\
int i;\
START_CRITICAL();\
for(i=0;i<(LEN);i++)\
{\
##NAME.buffer[##NAME.wi] = *(((UCHAR*)(S))+i);\
##NAME.wi++;\
if(##NAME.wi == ##NAME.max) ##NAME.wi=0;\
}\
END_CRITICAL();\
}
/* 从FIFO读消息 */
// Prototype: void MSG_DEQUEUE(char *NAME, TYPE *BUF, int BUFSIZE, int READ)
#define MSG_DEQUEUE(NAME,BUF,SIZE,READ)\
{\
int i=0;\
START_CRITICAL();\
READ=0;\
while(##NAME.ri != ##NAME.wi && i < SIZE)\
{\
*(BUF+i) = *(##NAME.buffer+##NAME.ri);\
i++;\
##NAME.ri++;\
if(##NAME.ri == ##NAME.max) ##NAME.ri=0;\
}\
READ = i;\
END_CRITICAL();\
}
/* 统计FIFO中消息的数量 */
// Prototype: void MSG_COUNT(char *NAME,int COUNT)
#define MSG_COUNT(NAME,COUNT)\
{\
int i=0;\
START_CRITICAL();\
if(##NAME.ri <= ##NAME.wi)\
COUNT = ##NAME.wi - ##NAME.ri;\
else\
COUNT = ##NAME.wi + (##NAME.max - ##NAME.ri);\
END_CRITICAL();\
}
/* 清空FIFO */
// Prototype: void MSG_FLUSH(char *NAME)
#define MSG_FLUSH(NAME)\
{\
START_CRITICAL();\
##NAME.wi = ##NAME.ri =0;\
END_CRITICAL();\
}
#endif // _MESSAGEOBJECT_H_