GameEngine/other/worker_old.md
2026-02-20 16:12:16 +01:00

2.2 KiB


#include <core.h>
#include <pthread.h>

static bool	done_flag = false;
static mtx_t done_mtx;

static bool	running_flag = false;
static mtx_t running_mtx;

static thrd_t *worker_queue;
static int		worker_size;

// Create Thread Pool (Workers)
// Queue Task
// Return Result

void	WorkerManager() {
	bool running = true;
	while (running) {
		assert(thrd_sleep(10, 0) == 0);
		switch (mtx_trylock(&running_mtx)) {
			case (thrd_success): {
				running = running_flag;
				mtx_unlock(&running_mtx);
				break;
			}
			case (thrd_error): {
				thrd_exit(-1);
				break;
			}
			default: {
				TraceLog(LOG_DEBUG, "running mutex busy");
				break;
			}
		}
		//process worker queue
	}
	for (int i = 0; i < worker_size; i++) {
		thrd_join(&worker_queue[i], NULL);
	}
	free(worker_queue);
	thrd_exit(0);
}

void	StartWorkerManager(int worker_number) {
	thrd_t worker_mgr_thrd;
	switch (thrd_create(&worker_mgr_thrd, WorkerManager, NULL)) {
		case (thrd_error): {
			TraceLog(LOG_ERROR, "WorkerManager Start Was Unsuccessful");
			//launch the engine in no thread mods;
			break;
		}
		case (thrd_nomem): {
			TraceLog(LOG_ERROR, "WorkerManager Start Was Unsuccessful: no memory could get allocated for new thread");
			assert(false);
			break;
		}
		default: {
			TraceLog(LOG_DEBUG, "WorkerManager Start Was Successful");
			break;
		}
	}
	worker_queue = malloc(sizeof(thrd_t) * worker_number);
	worker_size = worker_number;
	assert(worker_queue);
	for (int i = 0; i < worker_number; i++) {
			switch (thrd_create(&worker_queue[i], WorkerManager, NULL)) {
			case (thrd_error): {
				TraceLog(LOG_ERROR, "Worker No.%i Start Was Unsuccessful", i);
				assert(false);
				break;
			}
			case (thrd_nomem): {
				TraceLog(LOG_ERROR, "Worker No.%i Start Was Unsuccessful: no memory could get allocated for new thread", i);
				assert(false);
				break;
			}
			default: {
				TraceLog(LOG_DEBUG, "Worker No.%i Start Was Successful", i);
				break;
			}
		}
	}
}

void	StopWorkerManager() {
	while (mtx_trylock(&running_mtx) != thrd_success) {
		thrd_sleep(11, 0);
	}
	running_flag = false;
	mtx_unlock(&running_mtx);
}