aboutsummaryrefslogtreecommitdiff
path: root/threadpool.c
blob: fb93a189fbbd3a9d1c4971ef52b7a258347ecd2b (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
 * Copyright 2018 Anton Khirnov <anton@khirnov.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <errno.h>
#include <omp.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <stdio.h>

#include "threadpool.h"

struct TPContext {
    unsigned int nb_threads;
};

void tp_free(TPContext **pctx)
{
    TPContext *ctx = *pctx;

    if (!ctx)
        return;

    free(ctx);
    *pctx = NULL;
}

int tp_init(TPContext **pctx, unsigned int nb_threads)
{
    TPContext *ctx = NULL;
    int ret;

    if (!nb_threads) {
        const char *env_threads = getenv("OMP_NUM_THREADS");
        if (env_threads) {
            nb_threads = strtol(env_threads, NULL, 0);
        }
#ifdef _SC_NPROCESSORS_ONLN
        else {
            long val = sysconf(_SC_NPROCESSORS_ONLN);
            if (val > 0)
                nb_threads = val;
        }
#endif

        if (!nb_threads) {
            ret = -EINVAL;
            goto fail;
        }
    }

    ctx = calloc(1, sizeof(*ctx));
    if (!ctx) {
        ret = -ENOMEM;
        goto fail;
    }

    omp_set_num_threads(nb_threads);

    ctx->nb_threads = nb_threads;

    *pctx = ctx;
    return 0;

fail:
    tp_free(&ctx);
    *pctx = NULL;
    return ret;
}

int tp_execute(TPContext *ctx, unsigned int nb_jobs,
               TPExecuteCallback func, void *func_arg)
{
#pragma omp parallel for
    for (unsigned int i = 0; i < nb_jobs; i++)
        func(func_arg, i, omp_get_thread_num());

    return 0;
}

unsigned int tp_get_nb_threads(TPContext *ctx)
{
    return ctx->nb_threads;
}