-
Notifications
You must be signed in to change notification settings - Fork 3
/
u_threads_win32.c
140 lines (110 loc) · 2.27 KB
/
u_threads_win32.c
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#include <stddef.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <process.h>
#include "u_threads.h"
static void __cdecl thread_func_wrapper(void *arg)
{
U_Thread *th = arg;
th->func(th->arg);
}
int U_thread_create(U_Thread *th, void (*func)(void *), void *arg)
{
uintptr_t ret;
unsigned stack_size;
th->func = func;
th->arg = arg;
th->thread = 0;
stack_size = 1 << 22; // 4 MB
ret = _beginthread(thread_func_wrapper, stack_size, th);
if (ret == -1L)
return 0;
th->thread = (void*)ret;
return 1;
}
int U_thread_join(U_Thread *th)
{
DWORD ret;
ret = WaitForSingleObject((HANDLE)th->thread, INFINITE);
if (ret == WAIT_OBJECT_0)
return 1;
return 0;
}
void U_thread_exit(int result)
{
(void)result;
_endthread();
}
void U_thread_msleep(unsigned long milliseconds)
{
if (milliseconds)
Sleep((DWORD)milliseconds);
}
int U_thread_mutex_init(U_Mutex *m)
{
m->mutex = (void*)CreateMutexW(NULL, FALSE, NULL);
if (m->mutex)
return 1;
return 0;
}
int U_thread_mutex_destroy(U_Mutex *m)
{
if (m->mutex)
{
CloseHandle(m->mutex);
m->mutex = 0;
return 1;
}
return 0;
}
int U_thread_mutex_lock(U_Mutex *m)
{
DWORD ret;
ret = WaitForSingleObject(m->mutex, INFINITE);
if (ret == WAIT_OBJECT_0)
return 1;
return 0;
}
int U_thread_mutex_trylock(U_Mutex *m)
{
DWORD ret;
ret = WaitForSingleObject(m->mutex, 0);
if (ret == WAIT_OBJECT_0)
return 1;
return 0;
}
int U_thread_mutex_unlock(U_Mutex *m)
{
if (ReleaseMutex(m->mutex))
return 1;
return 0;
}
int U_thread_semaphore_init(U_Semaphore *s, unsigned initial_value)
{
s->sem = (void*)CreateSemaphoreW(NULL, (LONG)initial_value, MAXLONG, NULL);
if (s->sem)
return 1;
return 0;
}
int U_thread_semaphore_destroy(U_Semaphore *s)
{
if (s->sem)
{
CloseHandle(s->sem);
s->sem = 0;
return 1;
}
return 0;
}
int U_thread_semaphore_wait(U_Semaphore *s)
{
if (WaitForSingleObject(s->sem, INFINITE) == WAIT_OBJECT_0)
return 1;
return 0;
}
int U_thread_semaphore_post(U_Semaphore *s)
{
if (ReleaseSemaphore(s->sem, 1, NULL))
return 1;
return 0;
}