1 /* 2 * Copyright 2020 Lag Free Games, LLC 3 * Copyright 2022 Yonggang Luo 4 * SPDX-License-Identifier: MIT 5 */ 6 7 #include <assert.h> 8 #include "rwlock.h" 9 10 #if defined(_WIN32) && !defined(HAVE_PTHREAD) 11 #include <windows.h> 12 static_assert(sizeof(struct u_rwlock) == sizeof(SRWLOCK), 13 "struct u_rwlock should have equal size with SRWLOCK"); 14 #endif 15 u_rwlock_init(struct u_rwlock * rwlock)16int u_rwlock_init(struct u_rwlock *rwlock) 17 { 18 #if defined(_WIN32) && !defined(HAVE_PTHREAD) 19 InitializeSRWLock((PSRWLOCK)(&rwlock->rwlock)); 20 return 0; 21 #else 22 return pthread_rwlock_init(&rwlock->rwlock, NULL); 23 #endif 24 } 25 u_rwlock_destroy(struct u_rwlock * rwlock)26int u_rwlock_destroy(struct u_rwlock *rwlock) 27 { 28 #if defined(_WIN32) && !defined(HAVE_PTHREAD) 29 return 0; 30 #else 31 return pthread_rwlock_destroy(&rwlock->rwlock); 32 #endif 33 } 34 u_rwlock_rdlock(struct u_rwlock * rwlock)35int u_rwlock_rdlock(struct u_rwlock *rwlock) 36 { 37 #if defined(_WIN32) && !defined(HAVE_PTHREAD) 38 AcquireSRWLockShared((PSRWLOCK)&rwlock->rwlock); 39 return 0; 40 #else 41 return pthread_rwlock_rdlock(&rwlock->rwlock); 42 #endif 43 } 44 u_rwlock_rdunlock(struct u_rwlock * rwlock)45int u_rwlock_rdunlock(struct u_rwlock *rwlock) 46 { 47 #if defined(_WIN32) && !defined(HAVE_PTHREAD) 48 ReleaseSRWLockShared((PSRWLOCK)&rwlock->rwlock); 49 return 0; 50 #else 51 return pthread_rwlock_unlock(&rwlock->rwlock); 52 #endif 53 } 54 u_rwlock_wrlock(struct u_rwlock * rwlock)55int u_rwlock_wrlock(struct u_rwlock *rwlock) 56 { 57 #if defined(_WIN32) && !defined(HAVE_PTHREAD) 58 AcquireSRWLockExclusive((PSRWLOCK)&rwlock->rwlock); 59 return 0; 60 #else 61 return pthread_rwlock_wrlock(&rwlock->rwlock); 62 #endif 63 } 64 u_rwlock_wrunlock(struct u_rwlock * rwlock)65int u_rwlock_wrunlock(struct u_rwlock *rwlock) 66 { 67 #if defined(_WIN32) && !defined(HAVE_PTHREAD) 68 ReleaseSRWLockExclusive((PSRWLOCK)&rwlock->rwlock); 69 return 0; 70 #else 71 return pthread_rwlock_unlock(&rwlock->rwlock); 72 #endif 73 } 74