summaryrefslogtreecommitdiff
path: root/src/util/thread/thread.h
blob: 766af4912a2c02a2e1cb815c9146439ed346e886 (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
100
#pragma once

#include <al/types.h>

#ifdef NAUNET_ON_WINDOWS
#include "../../winwrap.h"
#else
#include <pthread.h>
#endif

#ifdef NAUNET_HAS_THREAD_CANCEL
enum {
    NNWT_THREAD_CANCEL_DEFERRED = PTHREAD_CANCEL_DEFERRED,
    NNWT_THREAD_CANCEL_ASYNCHRONOUS = PTHREAD_CANCEL_ASYNCHRONOUS
};
#endif

#ifdef NAUNET_ON_WINDOWS
enum {
    NNWT_THREAD_SCHED_OTHER = 0,
    NNWT_THREAD_SCHED_FIFO,
    NNWT_THREAD_SCHED_RR
};
#else
enum {
    NNWT_THREAD_SCHED_OTHER = SCHED_OTHER,
    NNWT_THREAD_SCHED_FIFO = SCHED_FIFO,
    NNWT_THREAD_SCHED_RR = SCHED_RR
};
#endif

struct nn_thread {
#ifdef NAUNET_ON_WINDOWS
    HANDLE thread;
#else
    pthread_t thread;
#endif
};

struct nn_mutex {
#ifdef NAUNET_ON_WINDOWS
    CRITICAL_SECTION mutex;
#else
    pthread_mutex_t mutex;
#endif
};

struct nn_cond {
#ifdef NAUNET_ON_WINDOWS
#ifdef NAUNET_WIN32_COMPAT_MODE
    HANDLE event;
#else
    CONDITION_VARIABLE cond;
#endif
#else
    pthread_cond_t cond;
#endif
    bool condition;
};

typedef f64 nn_os_tstamp;

#define NNWT_TS_FROM_USEC(usec) ((usec) * 1e-6)

#ifdef NAUNET_ON_WINDOWS
#define NNWT_THREADCALL __stdcall
typedef unsigned long nn_thread_result;
#else
#define NNWT_THREADCALL
typedef void * nn_thread_result;
#endif

#define nn_locked_assert(expr, lock) al_assert(!nn_mutex_lock(lock) && (expr) && !nn_mutex_unlock(lock))

typedef nn_thread_result (NNWT_THREADCALL * nn_thread_func)(void *);

void nn_thread_sleep(nn_os_tstamp delay);

void nn_thread_create(struct nn_thread *thread, nn_thread_func func, void *userdata);

void nn_thread_set_priority(s32 policy, s32 priority);
void nn_thread_set_name(const char *name);

void nn_thread_join(struct nn_thread *thread);
#ifdef NAUNET_HAS_THREAD_CANCEL
void nn_thread_cancel(struct nn_thread *thread);
void nn_thread_setcanceltype(s32 type);
#endif
//void nn_thread_detach(struct nn_thread *thread);

void nn_mutex_init(struct nn_mutex *mutex);
s32 nn_mutex_lock(struct nn_mutex *mutex);
s32 nn_mutex_unlock(struct nn_mutex *mutex);
void nn_mutex_destroy(struct nn_mutex *mutex);

void nn_cond_init(struct nn_cond *cond);
void nn_cond_wait(struct nn_cond *cond, struct nn_mutex *mutex);
bool nn_cond_is_waiting(struct nn_cond *cond);
void nn_cond_signal(struct nn_cond *cond);
void nn_cond_destroy(struct nn_cond *cond);