一个简单的栈操作

一个简单的栈操作,对于什么是栈就不在描述了,具体代码如下:
不考虑多线程任务同步情况:
  1. #ifndef _STACK_H_
  2. #define _STACK_H_
  3. #define STACK_INIT(type,size,name) \
  4. type stack_##name[size];\
  5. static int top_##name = 0
  6. #define POP(name) \
  7. (top_##name > 0 ? stack_##name[--top_##name] : NULL)\
  8. #define PUSH(name,value)\
  9. (top_##name < (sizeof(stack_##name)) ? \
  10. stack_##name[top_##name++] = value : 0)\
  11. #define FIRST(name)\
  12. (top_##name > 0 ? stack_##name[top_##name-1] : NULL)\
  13. #endif

同步版本的如下:
  1. #ifndef _STACK_H_
  2. #define _STACK_H_
  3. #include <alsa/iatomic.h>
  4. #include <pthread.h>
  5. static void* stack_my[128];
  6. static int top_my = 0;
  7. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  8. static inline void *POP()
  9. {
  10. void *ptr;
  11. pthread_mutex_lock(&mutex);
  12. ptr = top_my > 0 ? stack_my[--top_my] : NULL;
  13. pthread_mutex_unlock(&mutex);
  14. return ptr;
  15. }
  16. static inline void* PUSH(void *value)
  17. {
  18. void *ptr;
  19. pthread_mutex_lock(&mutex);
  20. ptr = top_my < 128 ? stack_my[top_my++] = value : 0;
  21. pthread_mutex_unlock(&mutex);
  22. return ptr;
  23. }
  24. #endif
给个简单测试的main.c
  1. #include <stdio.h>
  2. #include "stack.h"
  3. int main()
  4. {
  5. STACK_INIT(int, 36, my);
  6. PUSH(my,11);
  7. PUSH(my,12);
  8. PUSH(my,13);
  9. PUSH(my,14);
  10. printf(" %d ",FIRST(my));
  11. printf(" %d ",POP(my));
  12. printf(" %d ",FIRST(my));
  13. printf(" %d ",POP(my));
  14. printf(" %d ",FIRST(my));
  15. printf(" %d ",POP(my));
  16. printf(" %d ",FIRST(my));
  17. printf(" %d ",POP(my));
  18. return 0;
  19. }

附件列表

     

    posted on 2017-08-28 11:29  cfzhang  阅读(253)  评论(0编辑  收藏  举报

    导航