dynmem_sample.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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: dynamic memory management
  13. *
  14. * This demo creates a dynamic thread to allocate and free memory.
  15. * Each time it allocates more memory, and it will end when it can't allocate any memory.
  16. *
  17. * read more:
  18. * https://www.rt-thread.io/document/site/memory/memory/#memory-management
  19. */
  20. #include <rtthread.h>
  21. #define THREAD_PRIORITY 25
  22. #define THREAD_STACK_SIZE 512
  23. #define THREAD_TIMESLICE 5
  24. /* thread #1 entry function*/
  25. void thread1_entry(void *parameter)
  26. {
  27. int i;
  28. char *ptr = RT_NULL; /* memory's pointer */
  29. for (i = 0; ; i++)
  30. {
  31. /* allocate memory of (1 << i) bytes */
  32. ptr = rt_malloc(1 << i);
  33. if (ptr != RT_NULL)
  34. {
  35. /* if memory allocated successfully */
  36. rt_kprintf("get memory :%d byte\n", (1 << i));
  37. rt_free(ptr); /* free memory */
  38. rt_kprintf("free memory :%d byte\n", (1 << i));
  39. ptr = RT_NULL;
  40. }
  41. else
  42. {
  43. rt_kprintf("try to get %d byte memory failed!\n", (1 << i));
  44. return;
  45. }
  46. }
  47. }
  48. int dynmem_sample(void)
  49. {
  50. rt_thread_t tid = RT_NULL;
  51. /* create thread #1 */
  52. tid = rt_thread_create("thread1",
  53. thread1_entry, RT_NULL,
  54. THREAD_STACK_SIZE,
  55. THREAD_PRIORITY,
  56. THREAD_TIMESLICE);
  57. /*start thread #1 */
  58. if (tid != RT_NULL)
  59. rt_thread_startup(tid);
  60. return 0;
  61. }
  62. /* export the msh command */
  63. MSH_CMD_EXPORT(dynmem_sample, dynmem sample);