]> git.lizzy.rs Git - dragonstd.git/commitdiff
Add flags
authorElias Fleckenstein <eliasfleckenstein@web.de>
Sun, 13 Feb 2022 15:25:40 +0000 (16:25 +0100)
committerElias Fleckenstein <eliasfleckenstein@web.de>
Sun, 13 Feb 2022 15:25:40 +0000 (16:25 +0100)
flag.c [new file with mode: 0644]
flag.h [new file with mode: 0644]

diff --git a/flag.c b/flag.c
new file mode 100644 (file)
index 0000000..e7d1a6f
--- /dev/null
+++ b/flag.c
@@ -0,0 +1,34 @@
+#include <stdlib.h>
+#include "flag.h"
+
+Flag *flag_create()
+{
+       Flag *flag = malloc(sizeof *flag);
+       flag->done = false;
+       pthread_cond_init(&flag->cv, NULL);
+       pthread_mutex_init(&flag->mtx, NULL);
+       return flag;
+}
+
+void flag_delete(Flag *flag)
+{
+       pthread_cond_destroy(&flag->cv);        
+       pthread_mutex_destroy(&flag->mtx);
+       free(flag);
+}
+
+void flag_wait(Flag *flag)
+{
+       pthread_mutex_lock(&flag->mtx);
+       if (! flag->done)
+               pthread_cond_wait(&flag->cv, &flag->mtx);
+       pthread_mutex_unlock(&flag->mtx);
+}
+
+void flag_set(Flag *flag)
+{
+       pthread_mutex_lock(&flag->mtx);
+       flag->done = true;
+       pthread_cond_broadcast(&flag->cv);
+       pthread_mutex_unlock(&flag->mtx);
+}
diff --git a/flag.h b/flag.h
new file mode 100644 (file)
index 0000000..61e0be2
--- /dev/null
+++ b/flag.h
@@ -0,0 +1,19 @@
+#ifndef _DRAGONSTD_FLAG_H_
+#define _DRAGONSTD_FLAG_H_
+
+#include <stdbool.h>
+#include <stdatomic.h>
+#include <pthread.h>
+
+typedef struct {
+       atomic_bool done;
+       pthread_cond_t cv;
+       pthread_mutex_t mtx;
+} Flag;
+
+Flag *flag_create();
+void flag_delete(Flag *flag);
+void flag_set(Flag *flag);
+void flag_wait(Flag *flag);
+
+#endif