summaryrefslogtreecommitdiffstats
path: root/04_exercise/threadpool.c
blob: 510e83e2c0dbf93010ca56f279e12508de838538 (plain) (blame)
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
#include "threadpool.h"
#include "arena_list.h"
#include "array.h"

#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define MAX_FUTURES 2048
typedef struct Thread {
    pthread_t pthread;
    size_t index;
} Thread;

typedef struct ThreadPool {
    /* TODO: benötigte Attribute hinzufügen */
    size_t size;
    Thread *threads;
    Node arena [MAX_FUTURES];
    ArenaList al;

} ThreadPool;

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) {
    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) {
    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;
    }
}