zoukankan      html  css  js  c++  java
  • 一个简单的栈操作

    一个简单的栈操作,对于什么是栈就不在描述了,具体代码如下:
    不考虑多线程任务同步情况:
    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. }

    附件列表

    • 相关阅读:
      阅读第十到十二章有感
      程序测试学习之5.2作业
      作业五——封装
      作业4 阅读《构建之法》第6 第7章有感
      汉堡包~~~
      作业3 阅读《构建之法》1-5章
      结对子实验——小学生四则运算
      小学生四则运算程序
      学会提问(转)
      error of “omission” and “commission”
    • 原文地址:https://www.cnblogs.com/cfzhang/p/cd79682c7fedebbc615920feb7eec6f1.html
    Copyright © 2011-2022 走看看