1 /* 2 * Copyright (c) 2023, Meta 3 * 4 * SPDX-License-Identifier: Apache-2.0 5 */ 6 7 #include <errno.h> 8 #include <threads.h> 9 10 #include <zephyr/kernel.h> 11 #include <zephyr/posix/pthread.h> 12 mtx_init(mtx_t * mutex,int type)13int mtx_init(mtx_t *mutex, int type) 14 { 15 int ret; 16 pthread_mutexattr_t attr; 17 pthread_mutexattr_t *attrp = NULL; 18 19 switch (type) { 20 case mtx_plain: 21 case mtx_timed: 22 break; 23 case mtx_plain | mtx_recursive: 24 case mtx_timed | mtx_recursive: 25 attrp = &attr; 26 ret = pthread_mutexattr_init(attrp); 27 __ASSERT_NO_MSG(ret == 0); 28 29 ret = pthread_mutexattr_settype(attrp, PTHREAD_MUTEX_RECURSIVE); 30 __ASSERT_NO_MSG(ret == 0); 31 break; 32 default: 33 return thrd_error; 34 } 35 36 switch (pthread_mutex_init(mutex, attrp)) { 37 case 0: 38 ret = thrd_success; 39 break; 40 default: 41 ret = thrd_error; 42 break; 43 } 44 45 if (attrp != NULL) { 46 (void)pthread_mutexattr_destroy(attrp); 47 } 48 49 return ret; 50 } 51 mtx_destroy(mtx_t * mutex)52void mtx_destroy(mtx_t *mutex) 53 { 54 (void)pthread_mutex_destroy(mutex); 55 } 56 mtx_lock(mtx_t * mutex)57int mtx_lock(mtx_t *mutex) 58 { 59 switch (pthread_mutex_lock(mutex)) { 60 case 0: 61 return thrd_success; 62 default: 63 return thrd_error; 64 } 65 } 66 mtx_timedlock(mtx_t * restrict mutex,const struct timespec * restrict time_point)67int mtx_timedlock(mtx_t *restrict mutex, const struct timespec *restrict time_point) 68 { 69 switch (pthread_mutex_timedlock(mutex, time_point)) { 70 case 0: 71 return thrd_success; 72 case ETIMEDOUT: 73 return thrd_timedout; 74 default: 75 return thrd_error; 76 } 77 } 78 mtx_trylock(mtx_t * mutex)79int mtx_trylock(mtx_t *mutex) 80 { 81 switch (pthread_mutex_trylock(mutex)) { 82 case 0: 83 return thrd_success; 84 case EBUSY: 85 return thrd_busy; 86 default: 87 return thrd_error; 88 } 89 } 90 mtx_unlock(mtx_t * mutex)91int mtx_unlock(mtx_t *mutex) 92 { 93 switch (pthread_mutex_unlock(mutex)) { 94 case 0: 95 return thrd_success; 96 default: 97 return thrd_error; 98 } 99 } 100