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 13 #include <stdatomic.h> 14 15 typedef struct { 16 atomic_int count; 17 } semaphore_t; 18 semaphore_init(semaphore_t * sem,int count)19void semaphore_init(semaphore_t *sem, int count) 20 { 21 atomic_init(&sem->count, count); 22 } 23 semaphore_wait(semaphore_t * sem)24void semaphore_wait(semaphore_t *sem) 25 { 26 int count; 27 do { 28 count = atomic_load(&sem->count); 29 } while (count == 0 || !atomic_compare_exchange_weak(&sem->count, &count, count - 1)); 30 } 31 semaphore_signal(semaphore_t * sem)32void semaphore_signal(semaphore_t *sem) 33 { 34 atomic_fetch_add(&sem->count, 1); 35 } 36 37 #endif /* __SEMAPHORE_H__ */ 38