summaryrefslogtreecommitdiff
path: root/src/engine/threads.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/engine/threads.c')
-rw-r--r--src/engine/threads.c91
1 files changed, 91 insertions, 0 deletions
diff --git a/src/engine/threads.c b/src/engine/threads.c
new file mode 100644
index 0000000..5afe155
--- /dev/null
+++ b/src/engine/threads.c
@@ -0,0 +1,91 @@
+#define ENGINE_THREADS_INTERNAL
+#include "engine/threads.h"
+#include <string.h>
+#include <stdlib.h>
+#include <assert.h>
+#include <stdio.h>
+
+void threads_init(struct threads *handler, size_t capacity) {
+ // maybe this will be a speed up?
+ // why am i micro optimizing here??????
+ // idk i just watched the eskil steenberg video about UB
+ memset(handler, 0, sizeof(*handler));
+
+ handler->threads = malloc(sizeof(*handler->threads) * capacity);
+ handler->args = malloc(sizeof(*handler->args) * capacity);
+ handler->capacity = capacity;
+ handler->count = 0;
+ handler->running_count = 0;
+ handler->engine_messages = NULL;
+ handler->go_args = NULL;
+ handler->position = NULL;
+}
+
+void threads_deinit(struct threads *handler) {
+ assert(handler->running_count == 0);
+ free(handler->threads);
+ free(handler->args);
+}
+
+void threads_reserve(struct threads *handler, size_t capacity) {
+ if (handler->capacity >= capacity) return;
+
+ handler->threads = realloc(
+ handler->threads,
+ sizeof(*handler->threads) * capacity
+ );
+ handler->args = realloc(
+ handler->args,
+ sizeof(*handler->args) * capacity
+ );
+ handler->capacity = capacity;
+}
+
+void threads_go(struct threads *handler) {
+ int running_count = handler->running_count;
+ for (int i = 0; i < running_count; i++) {
+ __threads_args_init(handler->args + i, handler, i);
+ pthread_create(
+ handler->threads + i,
+ NULL,
+ engine_thread,
+ handler->args + i
+ );
+ }
+}
+
+bool threads_go_loop(struct threads *handler) {
+ // idk maybe do something while waiting for calculations to flow in
+}
+
+bool threads_all_done(struct threads *handler) {
+ int running_count = handler->running_count;
+ assert(running_count > 0);
+ for (int i = 0; i < running_count; i++) {
+ if (atomic_load(&handler->args[i].finished) == 1) continue;
+ return false;
+ }
+ return true;
+}
+
+void threads_cleanup(struct threads *handler) {
+ int running_count = handler->running_count;
+ for (int i = 0; i < running_count; i++) {
+ __threads_args_init(handler->args + i, handler, i);
+ pthread_cancel(handler->threads[i]);
+ }
+ handler->running_count = 0;
+}
+
+void __threads_args_init(
+ struct thread_args* args,
+ struct threads *handler,
+ int i
+) {
+ atomic_init(&args->stop, 0);
+ atomic_init(&args->finished, 0);
+ args->id = i;
+ args->position = handler->position;
+ args->go_args = handler->go_args;
+ args->message = handler->engine_messages->data[i];
+}