memp_sample.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * Copyright (c) 2006-2022, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2018-08-24 yangjie the first version
  9. * 2020-10-17 Meco Man translate to English comment
  10. */
  11. /*
  12. * Demo: memory pool
  13. *
  14. * This demo creates one memory pool and two threads:
  15. * 1) thread #1: allocate memory pool
  16. * 2) thread #2: free memory pool
  17. *
  18. * read more:
  19. * https://www.rt-thread.io/document/site/memory/memory/#memory-pool
  20. */
  21. #include <rtthread.h>
  22. static rt_uint8_t *ptr[50];
  23. static rt_uint8_t mempool[4096];
  24. static struct rt_mempool mp;
  25. #define THREAD_PRIORITY 25
  26. #define THREAD_STACK_SIZE 512
  27. #define THREAD_TIMESLICE 5
  28. /* thread handler */
  29. static rt_thread_t tid1 = RT_NULL;
  30. static rt_thread_t tid2 = RT_NULL;
  31. /* thread #1 entry function */
  32. static void thread1_mp_alloc(void *parameter)
  33. {
  34. int i;
  35. for (i = 0 ; i < 50 ; i++)
  36. {
  37. if (ptr[i] == RT_NULL)
  38. {
  39. /* allocate memory from the memory pool */
  40. ptr[i] = rt_mp_alloc(&mp, RT_WAITING_FOREVER);
  41. if (ptr[i] != RT_NULL)
  42. rt_kprintf("allocate No.%d\n", i);
  43. }
  44. }
  45. }
  46. /* thread #2 entry function */
  47. static void thread2_mp_release(void *parameter)
  48. {
  49. int i;
  50. rt_kprintf("thread2 try to release block\n");
  51. for (i = 0; i < 50 ; i++)
  52. {
  53. /* free all memory */
  54. if (ptr[i] != RT_NULL)
  55. {
  56. rt_kprintf("release block %d\n", i);
  57. rt_mp_free(ptr[i]);
  58. ptr[i] = RT_NULL;
  59. }
  60. }
  61. }
  62. int mempool_sample(void)
  63. {
  64. int i;
  65. for (i = 0; i < 50; i ++) ptr[i] = RT_NULL;
  66. /* initiate memory pool */
  67. rt_mp_init(&mp, "mp1", &mempool[0], sizeof(mempool), 80);
  68. /* create thread #1 */
  69. tid1 = rt_thread_create("thread1", thread1_mp_alloc, RT_NULL,
  70. THREAD_STACK_SIZE,
  71. THREAD_PRIORITY, THREAD_TIMESLICE);
  72. if (tid1 != RT_NULL)
  73. rt_thread_startup(tid1); /* start thread #1 */
  74. /* create thread #2 */
  75. tid2 = rt_thread_create("thread2", thread2_mp_release, RT_NULL,
  76. THREAD_STACK_SIZE,
  77. THREAD_PRIORITY + 1, THREAD_TIMESLICE);
  78. if (tid2 != RT_NULL)
  79. rt_thread_startup(tid2); /* start thread #2 */
  80. return 0;
  81. }
  82. /* export the msh command */
  83. MSH_CMD_EXPORT(mempool_sample, mempool sample);