1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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];
}
|