pthread_mutex.c (2566B)
1 /* Copyright (C) 2013-2023, 2025 Vincent Forest (vaplv@free.fr) 2 * 3 * The RSys library is free software: you can redistribute it and/or modify 4 * it under the terms of the GNU General Public License as published 5 * by the Free Software Foundation, either version 3 of the License, or 6 * (at your option) any later version. 7 * 8 * The RSys library is distributed in the hope that it will be useful, 9 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * GNU General Public License for more details. 12 * 13 * You should have received a copy of the GNU General Public License 14 * along with the RSys library. If not, see <http://www.gnu.org/licenses/>. */ 15 16 #define _POSIX_C_SOURCE 200112L /* Spin lock and mutex rw */ 17 #include "../mem_allocator.h" 18 #include "../mutex.h" 19 #include <pthread.h> 20 21 #ifdef NDEBUG 22 #define PTHREAD(Func) pthread_##Func 23 #else 24 #define PTHREAD(Func) ASSERT(pthread_##Func == 0) 25 #endif 26 27 /******************************************************************************* 28 * Mutex 29 ******************************************************************************/ 30 struct mutex* 31 mutex_create(void) 32 { 33 pthread_mutex_t* mutex = mem_alloc(sizeof(pthread_mutex_t)); 34 if(mutex) 35 PTHREAD(mutex_init(mutex, NULL)); 36 return (struct mutex*)mutex; 37 } 38 39 void 40 mutex_destroy(struct mutex* mutex) 41 { 42 ASSERT(mutex); 43 PTHREAD(mutex_destroy((pthread_mutex_t*)mutex)); 44 mem_rm(mutex); 45 } 46 47 void 48 mutex_lock(struct mutex* mutex) 49 { 50 ASSERT(mutex); 51 PTHREAD(mutex_lock((pthread_mutex_t*)mutex)); 52 } 53 54 void 55 mutex_unlock(struct mutex* mutex) 56 { 57 ASSERT(mutex); 58 PTHREAD(mutex_unlock((pthread_mutex_t*)mutex)); 59 } 60 61 /******************************************************************************* 62 * Read Write mutex 63 ******************************************************************************/ 64 struct mutex_rw* 65 mutex_rw_create(void) 66 { 67 pthread_rwlock_t* mutex = mem_alloc(sizeof(pthread_rwlock_t)); 68 if(mutex) 69 PTHREAD(rwlock_init(mutex, NULL)); 70 return (struct mutex_rw*)mutex; 71 } 72 73 void 74 mutex_rw_destroy(struct mutex_rw* mutex) 75 { 76 ASSERT(mutex); 77 PTHREAD(rwlock_destroy((pthread_rwlock_t*)mutex)); 78 mem_rm(mutex); 79 } 80 81 void 82 mutex_rw_rlock(struct mutex_rw* mutex) 83 { 84 ASSERT(mutex); 85 PTHREAD(rwlock_rdlock((pthread_rwlock_t*)mutex)); 86 } 87 88 void 89 mutex_rw_wlock(struct mutex_rw* mutex) 90 { 91 ASSERT(mutex); 92 PTHREAD(rwlock_wrlock((pthread_rwlock_t*)mutex)); 93 } 94 95 void 96 mutex_rw_unlock(struct mutex_rw* mutex) 97 { 98 ASSERT(mutex); 99 PTHREAD(rwlock_unlock((pthread_rwlock_t*)mutex)); 100 } 101 102 #undef PTHREAD