aboutsummaryrefslogtreecommitdiff
path: root/include/std/thread.h
blob: 356ebf0b1192755406b587c50ecd55e227b151e0 (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
#ifndef AMALGAM_THREAD_H
#define AMALGAM_THREAD_H

#include "misc.h"
#include "types.h"
#include "defs.h"
#include <pthread.h>

typedef void* (AmalThreadCallbackFunc)(void *userdata);

#define AMAL_THREAD_OK 0
/* General error */
#define AMAL_THREAD_ERR -1
#define AMAL_THREAD_NOT_JOINABLE -23

/*#define AMAL_MUTEX_DEBUG*/

struct amal_thread {
    pthread_t thread_id;
    pthread_attr_t thread_attr;
    const char *name;
    bool cancellable;
    bool destroyable;
};

typedef enum {
    AMAL_THREAD_JOINABLE,
    AMAL_THREAD_DETACHED
} amal_thread_type;

struct amal_mutex {
    pthread_mutex_t mutex;
    #ifdef AMAL_MUTEX_DEBUG
    const char *lock_identifier;
    #endif
    bool locked;
    pthread_t owner_thread;
};

CHECK_RESULT int amal_thread_create(amal_thread *self, amal_thread_type thread_type, const char *name, AmalThreadCallbackFunc callback_func, void *userdata);
/* Safe to call multiple times */
CHECK_RESULT int amal_thread_deinit(amal_thread *self);
CHECK_RESULT int amal_thread_detach(amal_thread *self);
CHECK_RESULT int amal_thread_join(amal_thread *self, void **result);

bool amal_thread_is_main();
/* Returns 0 if the number of usable threads is unknown */
int amal_get_usable_thread_count();

void amal_mutex_init(amal_mutex *self);
void amal_mutex_deinit(amal_mutex *self);
CHECK_RESULT int amal_mutex_lock(amal_mutex *self, const char *lock_identifier);
/* Safe to call unlock when another thread owns the lock or if the lock is not locked */
CHECK_RESULT int amal_mutex_unlock(amal_mutex *self);
void amal_mutex_tryunlock(amal_mutex *self);

#endif