From fad28509e7463082a508b761c797773538df7d27 Mon Sep 17 00:00:00 2001 From: Stefan Zabka Date: Thu, 11 Jun 2020 01:00:32 +0200 Subject: First ideas --- 04_exercise/threadpool.c | 69 +++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 62 insertions(+), 7 deletions(-) (limited to '04_exercise/threadpool.c') diff --git a/04_exercise/threadpool.c b/04_exercise/threadpool.c index 3172147..510e83e 100644 --- a/04_exercise/threadpool.c +++ b/04_exercise/threadpool.c @@ -1,23 +1,78 @@ #include "threadpool.h" +#include "arena_list.h" +#include "array.h" +#include +#include +#include #include #include -#include + +#define MAX_FUTURES 2048 +typedef struct Thread { + pthread_t pthread; + size_t index; +} Thread; typedef struct ThreadPool { - /* TODO: benötigte Attribute hinzufügen */ + /* TODO: benötigte Attribute hinzufügen */ + size_t size; + Thread *threads; + Node arena [MAX_FUTURES]; + ArenaList al; + } ThreadPool; -/* TODO: interne, globale Variablen hinzufügen */ +ThreadPool threadPool; /* TODO: interne Hilfsfunktionen hinzufügen */ +void * poolWorkerFunc(void * v_index) { + size_t index = * (size_t *) v_index; + printf("Thread %zu started", index); + return NULL; +} int tpInit(size_t size) { - return 0; + threadPool.size = size; + arrayInit(threadPool.threads); + alInit(threadPool.arena, MAX_FUTURES); + for (size_t i = 0; i < size; ++i) { + arrayPush(threadPool.threads); + int status; + threadPool.threads[i].index = i; + if ((status = pthread_create(&threadPool.threads[i].pthread, NULL, + poolWorkerFunc, &threadPool.threads[i].index)) < 0) { + return status; + } + } + return 0; } -void tpRelease(void) {} +void tpRelease(void) { + for (size_t i = 0; i < threadPool.size; ++i) { + if (pthread_cancel(threadPool.threads[i].pthread) != 0) { + perror("Thread doesn't exist anymore"); + exit(-1); + } + } + for (size_t i = 0; i < threadPool.size; ++i) { + int status; + if ((status = pthread_join(threadPool.threads[i].pthread, NULL)) != 0) { + perror("An error occured while joining the threads"); + exit(status); + } + } +} + +void tpAsync(Future *future) { + alPush(&threadPool.al, (void *) future); +} + +void tpAwait(Future *future) { + if(atomic_load(&future->status) == FUT_DONE) { + alRemoveElem(&threadPool.al, (void *) future); + return; + } +} -void tpAsync(Future *future) {} -void tpAwait(Future *future) {} -- cgit v1.2.3-54-g00ecf