semaphore.h 760 B

12345678910111213141516171819202122232425262728293031323334353637
  1. /*
  2. * Copyright (c) 2006-2023, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2023-03-24 WangXiaoyao Complete testcase for synchronization
  9. */
  10. #ifndef __SEMAPHORE_H__
  11. #define __SEMAPHORE_H__
  12. #include <stdatomic.h>
  13. typedef struct {
  14. atomic_int count;
  15. } semaphore_t;
  16. void semaphore_init(semaphore_t *sem, int count)
  17. {
  18. atomic_init(&sem->count, count);
  19. }
  20. void semaphore_wait(semaphore_t *sem)
  21. {
  22. int count;
  23. do {
  24. count = atomic_load(&sem->count);
  25. } while (count == 0 || !atomic_compare_exchange_weak(&sem->count, &count, count - 1));
  26. }
  27. void semaphore_signal(semaphore_t *sem)
  28. {
  29. atomic_fetch_add(&sem->count, 1);
  30. }
  31. #endif /* __SEMAPHORE_H__ */