sem.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. */
  9. #include <pthread.h>
  10. #include <semaphore.h>
  11. #include <stdio.h>
  12. static sem_t sema;
  13. static void* other_thread()
  14. {
  15. printf("other_thread here!\n");
  16. sleep(1);
  17. while (1)
  18. {
  19. printf("other_thread: sem_post...\n");
  20. if(sem_post(&sema) == -1)
  21. printf("sem_post failed\n");
  22. sleep(1);
  23. }
  24. printf("other_thread dies!\n");
  25. pthread_exit(0);
  26. }
  27. static void test_thread(void* parameter)
  28. {
  29. pthread_t tid;
  30. printf("main thread here!\n");
  31. printf("sleep 5 seconds...");
  32. sleep(5);
  33. printf("done\n");
  34. sem_init(&sema, 0, 0);
  35. /* create the "other" thread */
  36. if(pthread_create(&tid, 0, &other_thread, 0)!=0)
  37. /* error */
  38. printf("pthread_create OtherThread failed.\n");
  39. else
  40. printf("created OtherThread=%x\n", tid);
  41. /* let the other thread run */
  42. while (1)
  43. {
  44. printf("Main: sem_wait...\n");
  45. if(sem_wait(&sema) == -1)
  46. printf("sem_wait failed\n");
  47. printf("Main back.\n\n");
  48. }
  49. pthread_exit(0);
  50. }
  51. #include <finsh.h>
  52. void libc_sem()
  53. {
  54. rt_thread_t tid;
  55. tid = rt_thread_create("semtest", test_thread, RT_NULL,
  56. 2048, 20, 5);
  57. if (tid != RT_NULL)
  58. {
  59. rt_thread_startup(tid);
  60. }
  61. }
  62. FINSH_FUNCTION_EXPORT(libc_sem, posix semaphore test);