poll workers for non-threaded support, emscripten main loop, remove twn_model.c

This commit is contained in:
veclavtalica
2025-02-21 21:16:15 +03:00
parent dc6b298532
commit d76ea06470
12 changed files with 105 additions and 289 deletions

View File

@ -2,12 +2,19 @@
#include "twn_workers_c.h"
#include "rendering/twn_draw_c.h"
#ifndef __EMSCRIPTEN__
SDL_sem *workers_job_semaphore;
static size_t workers_pool_size;
static SDL_mutex *workers_mutex;
static bool workers_should_exit;
static SDL_sem *workers_exit_semaphore; /* should come to count of `workers_pool_size` */
static bool workers_should_exit;
#else
/* accomulate to late poll from main thread itself */
static uint32_t workers_job_count;
#endif
static size_t workers_pool_size;
/* logic is such that when job is posted, worker threads attempt to grab it from any possible entry point */
/* if it did something, which is signaled by `true` return, go back to waiting on semaphore, so that it's decremented properly */
@ -15,6 +22,7 @@ static int worker_thread(void *udata) {
(void)udata;
while (true) {
#ifndef __EMSCRIPTEN__
/* check whether loop should end */
SDL_LockMutex(workers_mutex);
if (workers_should_exit) {
@ -26,6 +34,11 @@ static int worker_thread(void *udata) {
/* wait and occasionally go back to check whether it all should end */
if (SDL_SemWaitTimeout(workers_job_semaphore, 100) == SDL_MUTEX_TIMEDOUT)
continue;
#else
if (workers_job_count <= 0)
break;
workers_job_count--;
#endif
/* process models, which will trigger texture loads */
if (models_load_workers_thread())
@ -35,8 +48,10 @@ static int worker_thread(void *udata) {
continue;
}
#ifndef __EMSCRIPTEN__
/* let the main thread collect it */
SDL_SemPost(workers_exit_semaphore);
#endif
return 0;
}
@ -50,7 +65,7 @@ bool workers_init(size_t worker_count) {
if (worker_count > MAX_WORKERS)
worker_count = MAX_WORKERS;
#ifndef EMSCRIPTEN
#ifndef __EMSCRIPTEN__
/* spawn a bunch of detached threads without references to them */
for (size_t i = 0; i < worker_count; ++i) {
SDL_Thread *thread = SDL_CreateThread(worker_thread, "worker", NULL);
@ -68,7 +83,7 @@ bool workers_init(size_t worker_count) {
void workers_deinit(void) {
#ifndef EMSCRIPTEN
#ifndef __EMSCRIPTEN__
SDL_LockMutex(workers_mutex);
workers_should_exit = true;
SDL_UnlockMutex(workers_mutex);
@ -83,3 +98,19 @@ void workers_deinit(void) {
#endif
workers_pool_size = 0;
}
void workers_add_job(void) {
#ifndef __EMSCRIPTEN__
SDL_SemPost(workers_job_semaphore);
#else
workers_job_count++;
#endif
}
void workers_poll(void) {
#ifdef __EMSCRIPTEN__
worker_thread(NULL);
#else
#endif
}