summaryrefslogtreecommitdiff
path: root/lib/lockfd.c
blob: eb59536d8c6fe7801d2b6838608b41d02f7b06dc (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
#include "lockfd.h"

#include <assert.h>
#include <pthread.h>

#include "xalloc.h"

static pthread_mutex_t **mutexes = NULL;

static pthread_mutex_t *get_mutex(int fd) {
    assert(fd < 3 && "todo: implement generically");

    if (!mutexes) {
        mutexes = xmalloc(3 * sizeof(char *));
        assert(mutexes);
    }

    if (!mutexes[fd]) {
        mutexes[fd] = xmalloc(sizeof(pthread_mutex_t));
        assert(mutexes[fd]);
        pthread_mutex_init(mutexes[fd], NULL); // create mutex
        assert(mutexes[fd]);
    }

    return mutexes[fd];
}

int lock_fd(int fd) { return pthread_mutex_lock(get_mutex(fd)); }

int unlock_fd(int fd) { return pthread_mutex_unlock(get_mutex(fd)); }

int lock_file(FILE *f) {
    assert(f);

    return lock_fd(fileno(f));
}

int unlock_file(FILE *f) {
    assert(f);

    return unlock_fd(fileno(f));
}