resource_id.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * Copyright (c) 2006-2021, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2021-08-25 RT-Thread First version
  9. * 2023-09-15 xqyjlj perf rt_hw_interrupt_disable/enable
  10. */
  11. #include <rthw.h>
  12. #include <rtthread.h>
  13. #include <resource_id.h>
  14. void resource_id_init(resource_id_t *mgr, int size, void **res)
  15. {
  16. if (mgr)
  17. {
  18. mgr->size = size;
  19. mgr->_res = res;
  20. mgr->noused = 0;
  21. mgr->_free = RT_NULL;
  22. rt_spin_lock_init(&(mgr->spinlock));
  23. }
  24. }
  25. int resource_id_get(resource_id_t *mgr)
  26. {
  27. rt_base_t level;
  28. void **cur;
  29. level = rt_spin_lock_irqsave(&(mgr->spinlock));
  30. if (mgr->_free)
  31. {
  32. cur = mgr->_free;
  33. mgr->_free = (void **)*mgr->_free;
  34. rt_spin_unlock_irqrestore(&(mgr->spinlock), level);
  35. return cur - mgr->_res;
  36. }
  37. else if (mgr->noused < mgr->size)
  38. {
  39. cur = &mgr->_res[mgr->noused++];
  40. rt_spin_unlock_irqrestore(&(mgr->spinlock), level);
  41. return cur - mgr->_res;
  42. }
  43. return -1;
  44. }
  45. void resource_id_put(resource_id_t *mgr, int no)
  46. {
  47. rt_base_t level;
  48. void **cur;
  49. if (no >= 0 && no < mgr->size)
  50. {
  51. level = rt_spin_lock_irqsave(&(mgr->spinlock));
  52. cur = &mgr->_res[no];
  53. *cur = (void *)mgr->_free;
  54. mgr->_free = cur;
  55. rt_spin_unlock_irqrestore(&(mgr->spinlock), level);
  56. }
  57. }