summaryrefslogtreecommitdiff
path: root/src/util/rwlock.c
blob: 1d215d320f201d4cc3dda203148b52bd70494196 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
 * Copyright 2020 Lag Free Games, LLC
 * Copyright 2022 Yonggang Luo
 * SPDX-License-Identifier: MIT
 */

#include <assert.h>
#include "rwlock.h"

#if defined(_WIN32) && !defined(HAVE_PTHREAD)
#include <windows.h>
static_assert(sizeof(struct u_rwlock) == sizeof(SRWLOCK),
   "struct u_rwlock should have equal size with SRWLOCK");
#endif

int u_rwlock_init(struct u_rwlock *rwlock)
{
#if defined(_WIN32) && !defined(HAVE_PTHREAD)
   InitializeSRWLock((PSRWLOCK)(&rwlock->rwlock));
   return 0;
#else
   return pthread_rwlock_init(&rwlock->rwlock, NULL);
#endif
}

int u_rwlock_destroy(struct u_rwlock *rwlock)
{
#if defined(_WIN32) && !defined(HAVE_PTHREAD)
   return 0;
#else
   return pthread_rwlock_destroy(&rwlock->rwlock);
#endif
}

int u_rwlock_rdlock(struct u_rwlock *rwlock)
{
#if defined(_WIN32) && !defined(HAVE_PTHREAD)
   AcquireSRWLockShared((PSRWLOCK)&rwlock->rwlock);
   return 0;
#else
   return pthread_rwlock_rdlock(&rwlock->rwlock);
#endif
}

int u_rwlock_rdunlock(struct u_rwlock *rwlock)
{
#if defined(_WIN32) && !defined(HAVE_PTHREAD)
   ReleaseSRWLockShared((PSRWLOCK)&rwlock->rwlock);
   return 0;
#else
   return pthread_rwlock_unlock(&rwlock->rwlock);
#endif
}

int u_rwlock_wrlock(struct u_rwlock *rwlock)
{
#if defined(_WIN32) && !defined(HAVE_PTHREAD)
   AcquireSRWLockExclusive((PSRWLOCK)&rwlock->rwlock);
   return 0;
#else
   return pthread_rwlock_wrlock(&rwlock->rwlock);
#endif
}

int u_rwlock_wrunlock(struct u_rwlock *rwlock)
{
#if defined(_WIN32) && !defined(HAVE_PTHREAD)
   ReleaseSRWLockExclusive((PSRWLOCK)&rwlock->rwlock);
   return 0;
#else
   return pthread_rwlock_unlock(&rwlock->rwlock);
#endif
}