Reduct  v4.0.5-1-g4851deb
A functional and immutable language.
Loading...
Searching...
No Matches
sync.h
Go to the documentation of this file.
1#ifndef REDUCT_SYNC_H
2#define REDUCT_SYNC_H 1
3
4#include <reduct/defs.h>
5
6#include <stdbool.h>
7#include <stdint.h>
8#include <threads.h>
9
10/**
11 * @file sync.h
12 * @brief Syncronization primitives.
13 * @defgroup sync Sync
14 *
15 * @{
16 */
17
18/**
19 * @brief Read-Write Mutex structure.
20 * @struct reduct_rwmutex_t
21 */
22typedef struct
23{
24 mtx_t mtx;
25 cnd_t cnd;
26 uint32_t readers;
28 bool writing;
30
31/**
32 * @brief Initialize a read-write mutex.
33 *
34 * @param rw Pointer to the rwmutex to initialize.
35 */
37{
38 mtx_init(&rw->mtx, mtx_plain);
39 cnd_init(&rw->cnd);
40 rw->readers = 0;
41 rw->writersWaiting = 0;
42 rw->writing = false;
43}
44
45/**
46 * @brief Destroy a read-write mutex.
47 *
48 * @param rw Pointer to the rwmutex to destroy.
49 */
51{
52 mtx_destroy(&rw->mtx);
53 cnd_destroy(&rw->cnd);
54}
55
56/**
57 * @brief Lock a rwmutex for reading.
58 *
59 * @param rw Pointer to the rwmutex to lock.
60 */
62{
63 mtx_lock(&rw->mtx);
64 while (rw->writing || rw->writersWaiting > 0)
65 {
66 cnd_wait(&rw->cnd, &rw->mtx);
67 }
68 rw->readers++;
69 mtx_unlock(&rw->mtx);
70}
71
72/**
73 * @brief Unlock a rwmutex after reading.
74 *
75 * @param rw Pointer to the rwmutex to unlock.
76 */
78{
79 mtx_lock(&rw->mtx);
80 rw->readers--;
81 if (rw->readers == 0)
82 {
83 cnd_broadcast(&rw->cnd);
84 }
85 mtx_unlock(&rw->mtx);
86}
87
88/**
89 * @brief Lock a rwmutex for writing.
90 *
91 * @param rw Pointer to the rwmutex to lock.
92 */
94{
95 mtx_lock(&rw->mtx);
96 rw->writersWaiting++;
97 while (rw->writing || rw->readers > 0)
98 {
99 cnd_wait(&rw->cnd, &rw->mtx);
100 }
101 rw->writersWaiting--;
102 rw->writing = true;
103 mtx_unlock(&rw->mtx);
104}
105
106/**
107 * @brief Unlock a rwmutex after writing.
108 *
109 * @param rw Pointer to the rwmutex to unlock.
110 */
112{
113 mtx_lock(&rw->mtx);
114 rw->writing = false;
115 cnd_broadcast(&rw->cnd);
116 mtx_unlock(&rw->mtx);
117}
118
119/** @} */
120
121#endif
static void reduct_rwmutex_read_lock(reduct_rwmutex_t *rw)
Lock a rwmutex for reading.
Definition sync.h:61
static void reduct_rwmutex_write_unlock(reduct_rwmutex_t *rw)
Unlock a rwmutex after writing.
Definition sync.h:111
static void reduct_rwmutex_read_unlock(reduct_rwmutex_t *rw)
Unlock a rwmutex after reading.
Definition sync.h:77
static void reduct_rwmutex_destroy(reduct_rwmutex_t *rw)
Destroy a read-write mutex.
Definition sync.h:50
static void reduct_rwmutex_write_lock(reduct_rwmutex_t *rw)
Lock a rwmutex for writing.
Definition sync.h:93
static void reduct_rwmutex_init(reduct_rwmutex_t *rw)
Initialize a read-write mutex.
Definition sync.h:36
Read-Write Mutex structure.
Definition sync.h:23
mtx_t mtx
Definition sync.h:24
uint32_t writersWaiting
Definition sync.h:27
cnd_t cnd
Definition sync.h:25
bool writing
Definition sync.h:28
uint32_t readers
Definition sync.h:26