]> git.lizzy.rs Git - dragonstd.git/blob - flag.h
Use proper format for size_t printf
[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 #include "list.h"      // for List
18
19 typedef struct {
20         /* protected */
21         atomic_bool set;     // whether the flag is set
22         /* private */
23         pthread_cond_t cnd;  // main condition variable
24         pthread_mutex_t mtx; // mutex to protect the main condition variable
25         List cvs;            // condition variables
26 } Flag;
27
28 void flag_ini(Flag *flag);
29 /*
30         Initializes the flag.
31
32         The flag should be uninitialized or deleted before passed to this function.
33         This function should be called before any other function is called on the flag.
34 */
35
36 void flag_dst(Flag *flag);
37 /*
38         Destroy the flag.
39
40         The refcount is unusable until reinitialized afterwards.
41 */
42
43 void flag_sub(Flag *flag, pthread_cond_t *cnd);
44 /*
45         [Thread Safe]
46         Subscribe condition variable cnd to flag.
47
48         The condition variable will be triggered when the flag is set.
49 */
50
51 void flag_uns(Flag *flag, pthread_cond_t *cnd);
52 /*
53         [Thread Safe]
54         Unsubscribe condition variable cnd from flag.
55
56         The condition variable will no longer be triggered when the flag is set.
57 */
58
59 void flag_set(Flag *flag);
60 /*
61         [Thread Safe]
62         Sets the flag.
63
64         This changes the flag state to be true and wakes up any threads waiting for it.
65         Afterwards, **the state cannot be changed back**.
66
67         This function can be called multiple times.
68 */
69
70 void flag_slp(Flag *flag);
71 /*
72         [Thread Safe]
73         Waits for the flag to be true.
74
75         This will sleep until the flag's state is changed to true, unless it is already set to
76                 true.
77 */
78
79 #endif // _DRAGONSTD_FLAG_H_