aboutsummaryrefslogtreecommitdiff
path: root/src/thread_mgmt.c
blob: 6a7934e5ba3c40780221ab4972cee143a050dd40 (plain)
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
#include <stdlib.h>
#include <pthread.h>
#include <assert.h>

#include "thread_mgmt.h"

typedef struct thread_ctx {
    int used;
    pthread_t thread;
    thread_cb fn;
    void *user_data;
} thread_ctx;

static size_t max_threads = 0;
static thread_ctx *threads = NULL;
static pthread_mutex_t list_mtx = PTHREAD_MUTEX_INITIALIZER;

static void *
thread_fn(void *arg);


void thread_manager_init(size_t __max_threads)
{
    max_threads = __max_threads;
    assert(max_threads > 0);
    assert(!threads);
    threads = (thread_ctx *) calloc(max_threads, sizeof(thread_ctx));
    assert(threads);
}

int thread_add(thread_cb fn, void *user_data)
{
    int rv = -1;

    assert(fn);
    pthread_mutex_lock(&list_mtx);
    for (size_t i = 0; i < max_threads; ++i) {
        if (threads[i].used)
            continue;
        threads[i].used = 1;
        threads[i].fn = fn;
        threads[i].user_data = user_data;
        rv = pthread_create(&threads[i].thread, NULL, &thread_fn, &threads[i]);
    }
    pthread_mutex_unlock(&list_mtx);
    return rv;
}

void thread_manager_free(void)
{
    assert(threads);
    free(threads);
    threads = NULL;
    max_threads = 0;
}

static void *
thread_fn(void *arg)
{
    (void) arg;
    return NULL;
}