不考虑多线程任务同步情况:
#ifndef _STACK_H_#define _STACK_H_#define STACK_INIT(type,size,name)type stack_##name[size];static int top_##name = 0#define POP(name)(top_##name > 0 ? stack_##name[--top_##name] : NULL)#define PUSH(name,value)(top_##name < (sizeof(stack_##name)) ?stack_##name[top_##name++] = value : 0)#define FIRST(name)(top_##name > 0 ? stack_##name[top_##name-1] : NULL)#endif
同步版本的如下:
#ifndef _STACK_H_#define _STACK_H_#include <alsa/iatomic.h>#include <pthread.h>static void* stack_my[128];static int top_my = 0;static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;static inline void *POP(){void *ptr;pthread_mutex_lock(&mutex);ptr = top_my > 0 ? stack_my[--top_my] : NULL;pthread_mutex_unlock(&mutex);return ptr;}static inline void* PUSH(void *value){void *ptr;pthread_mutex_lock(&mutex);ptr = top_my < 128 ? stack_my[top_my++] = value : 0;pthread_mutex_unlock(&mutex);return ptr;}#endif
给个简单测试的main.c
#include <stdio.h>#include "stack.h"int main(){STACK_INIT(int, 36, my);PUSH(my,11);PUSH(my,12);PUSH(my,13);PUSH(my,14);printf(" %d ",FIRST(my));printf(" %d ",POP(my));printf(" %d ",FIRST(my));printf(" %d ",POP(my));printf(" %d ",FIRST(my));printf(" %d ",POP(my));printf(" %d ",FIRST(my));printf(" %d ",POP(my));return 0;}