]> git.lizzy.rs Git - dragonstd.git/blob - flag.h
Fix missing lock release in map_trv
[dragonstd.git] / flag.h
1 /*
2         Flag
3         ----
4
5         A flag is a data structure that can be used to syncronize a boolean across multiple
6                 threads.
7
8         The flag's state can be set, read and waited for in a thread safe manner.
9 */
10
11 #ifndef _DRAGONSTD_FLAG_H_ // include guard
12 #define _DRAGONSTD_FLAG_H_
13
14 #include <pthread.h>   // for pthread_mutex_t, pthread_cond_t
15 #include <stdatomic.h> // for atomic_bool
16 #include <stdbool.h>   // for bool
17
18 typedef struct {
19         /* protected */
20         atomic_bool set;     // whether the flag is set
21         /* private */
22         pthread_cond_t cnd;  // condition variable used for waiting
23         pthread_mutex_t mtx; // mutex to protect the condition variable
24 } Flag;
25
26 void flag_ini(Flag *flag);
27 /*
28         Initializes the flag.
29
30         The flag should be uninitialized or deleted before passed to this function.
31         This function should be called before any other function is called on the flag.
32 */
33
34 void flag_dst(Flag *flag);
35 /*
36         Destroy the flag.
37
38         The refcount is unusable until reinitialized afterwards.
39 */
40
41 void flag_set(Flag *flag);
42 /*
43         [Thread Safe]
44         Sets the flag.
45
46         This changes the flag state to be true and wakes up any threads waiting for it.
47         Afterwards, **the state cannot be changed back**.
48
49         This function can be called multiple times.
50 */
51
52 void flag_slp(Flag *flag);
53 /*
54         [Thread Safe]
55         Waits for the flag to be true.
56
57         This will sleep until the flag's state is changed to true, unless it is already set to
58                 true.
59 */
60
61 #endif // _DRAGONSTD_FLAG_H_