Queue.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * File : Queue.h
  3. * This file is part of RT-Thread RTOS
  4. * COPYRIGHT (C) 2016, RT-Thread Development Team
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License along
  17. * with this program; if not, write to the Free Software Foundation, Inc.,
  18. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. *
  20. * Change Logs:
  21. * Date Author Notes
  22. * 2016/10/1 Bernard The first version
  23. */
  24. #pragma once
  25. #include <stdint.h>
  26. #include <string.h>
  27. #include <rtthread.h>
  28. namespace rtthread {
  29. /**
  30. * The Queue class allow to control, send, receive, or wait for messages.
  31. * A message can be a integer or pointer value to a certain type T that is send
  32. * to a thread or interrupt service routine.
  33. * @param T data type of a single message element.
  34. * @param queue_sz maximum number of messages in queue.
  35. */
  36. template<typename T, uint32_t queue_sz>
  37. class Queue
  38. {
  39. public:
  40. /** Create and initialise a message Queue. */
  41. Queue()
  42. {
  43. rt_mq_init(&mID, "mq", mPool, sizeof(T), sizeof(mPool), RT_IPC_FLAG_FIFO);
  44. };
  45. ~Queue()
  46. {
  47. rt_mq_detach(&mID);
  48. };
  49. /** Put a message in a Queue.
  50. @param data message pointer.
  51. @param millisec timeout value or 0 in case of no time-out. (default: 0)
  52. @return status code that indicates the execution status of the function.
  53. */
  54. rt_err_t put(T& data, int32_t millisec = 0)
  55. {
  56. return rt_mq_send(&mID, &data, sizeof(data));
  57. }
  58. /** Get a message or Wait for a message from a Queue.
  59. @param millisec timeout value or 0 in case of no time-out. (default: osWaitForever).
  60. @return bool .
  61. */
  62. bool get(T& data, int32_t millisec = WAIT_FOREVER)
  63. {
  64. rt_int32_t tick;
  65. if (millisec < 0)
  66. tick = -1;
  67. else
  68. tick = rt_tick_from_millisecond(millisec);
  69. return rt_mq_recv(&mID, &data, sizeof(data), tick) == RT_EOK;
  70. }
  71. private:
  72. struct rt_messagequeue mID;
  73. char mPool[(sizeof(struct rt_messagequeue)+sizeof(T)) * queue_sz];
  74. };
  75. }