-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathc89threads.c
1785 lines (1402 loc) · 46.7 KB
/
c89threads.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define C89THREAD_IMPLEMENTATION
#include "c89threads.h"
/**************************************************************************************************
Implementation
**************************************************************************************************/
#if defined(C89THREAD_IMPLEMENTATION)
/* Win32 */
#if defined(C89THREAD_WIN32)
#include <windows.h>
#include <limits.h> /* For LONG_MAX */
#ifndef C89THREAD_MALLOC
#define C89THREAD_MALLOC(sz) HeapAlloc(GetProcessHeap(), 0, (sz))
#endif
#ifndef C89THREAD_REALLOC
#define C89THREAD_REALLOC(p, sz) (((sz) > 0) ? ((p) ? HeapReAlloc(GetProcessHeap(), 0, (p), (sz)) : HeapAlloc(GetProcessHeap(), 0, (sz))) : ((VOID*)(size_t)(HeapFree(GetProcessHeap(), 0, (p)) & 0)))
#endif
#ifndef C89THREAD_FREE
#define C89THREAD_FREE(p) HeapFree(GetProcessHeap(), 0, (p))
#endif
static int c89thrd_result_from_GetLastError(DWORD error)
{
switch (error)
{
case ERROR_SUCCESS: return c89thrd_success;
case ERROR_NOT_ENOUGH_MEMORY: return c89thrd_nomem;
case ERROR_SEM_TIMEOUT: return c89thrd_timedout;
case ERROR_BUSY: return c89thrd_busy;
default: break;
}
return c89thrd_error;
}
static time_t c89timespec_to_milliseconds(const struct timespec ts)
{
LONGLONG milliseconds;
milliseconds = ((ts.tv_sec * 1000) + (ts.tv_nsec / 1000000));
if ((ts.tv_nsec % 1000000) != 0) {
milliseconds += 1; /* We truncated a sub-millisecond amount of time. Add an extra millisecond to meet the minimum duration requirement. */
}
return (time_t)milliseconds;
}
static time_t c89timespec_diff_milliseconds(const struct timespec tsA, const struct timespec tsB)
{
return (unsigned int)c89timespec_to_milliseconds(c89timespec_diff(tsA, tsB));
}
typedef struct
{
c89thrd_start_t func;
void* arg;
c89thread_entry_exit_callbacks entryExitCallbacks;
c89thread_allocation_callbacks allocationCallbacks;
int usingCustomAllocator;
} c89thrd_start_data_win32;
static unsigned long WINAPI c89thrd_start_win32(void* pUserData)
{
c89thrd_start_data_win32* pStartData = (c89thrd_start_data_win32*)pUserData;
c89thread_entry_exit_callbacks entryExitCallbacks;
c89thrd_start_t func;
void* arg;
unsigned long result;
entryExitCallbacks = pStartData->entryExitCallbacks;
if (entryExitCallbacks.onEntry != NULL) {
entryExitCallbacks.onEntry(entryExitCallbacks.pUserData);
}
/* Make sure we make a copy of the start data here. That way we can free pStartData straight away (it was allocated in c89thrd_create()). */
func = pStartData->func;
arg = pStartData->arg;
/* We should free the data pointer before entering into the start function. That way when c89thrd_exit() is called we don't leak. */
c89thread_free(pStartData, (pStartData->usingCustomAllocator) ? NULL : &pStartData->allocationCallbacks);
result = (unsigned long)func(arg);
if (entryExitCallbacks.onExit != NULL) {
entryExitCallbacks.onExit(entryExitCallbacks.pUserData);
}
return result;
}
int c89thrd_create_ex(c89thrd_t* thr, c89thrd_start_t func, void* arg, const c89thread_entry_exit_callbacks* pEntryExitCallbacks, const c89thread_allocation_callbacks* pAllocationCallbacks)
{
HANDLE hThread;
c89thrd_start_data_win32* pData; /* <-- Needs to be allocated on the heap to ensure the data doesn't get trashed before the thread is entered. */
if (thr == NULL) {
return c89thrd_error;
}
*thr = NULL; /* Safety. */
if (func == NULL) {
return c89thrd_error;
}
pData = (c89thrd_start_data_win32*)c89thread_malloc(sizeof(*pData), pAllocationCallbacks); /* <-- This will be freed when c89thrd_start_win32() is entered. */
if (pData == NULL) {
return c89thrd_nomem;
}
pData->func = func;
pData->arg = arg;
if (pEntryExitCallbacks != NULL) {
pData->entryExitCallbacks = *pEntryExitCallbacks;
} else {
pData->entryExitCallbacks.onEntry = NULL;
pData->entryExitCallbacks.onExit = NULL;
pData->entryExitCallbacks.pUserData = NULL;
}
if (pAllocationCallbacks != NULL) {
pData->allocationCallbacks = *pAllocationCallbacks;
pData->usingCustomAllocator = 1;
} else {
pData->allocationCallbacks.onMalloc = NULL;
pData->allocationCallbacks.onRealloc = NULL;
pData->allocationCallbacks.onFree = NULL;
pData->allocationCallbacks.pUserData = NULL;
pData->usingCustomAllocator = 0;
}
hThread = CreateThread(NULL, 0, c89thrd_start_win32, pData, 0, NULL);
if (hThread == NULL) {
c89thread_free(pData, pAllocationCallbacks);
return c89thrd_result_from_GetLastError(GetLastError());
}
*thr = (c89thrd_t)hThread;
return c89thrd_success;
}
int c89thrd_create(c89thrd_t* thr, c89thrd_start_t func, void* arg)
{
return c89thrd_create_ex(thr, func, arg, NULL, NULL);
}
int c89thrd_equal(c89thrd_t lhs, c89thrd_t rhs)
{
/*
Annoyingly, GetThreadId() is not defined for Windows XP. Need to conditionally enable this. I'm
not sure how to do this any other way, so I'm falling back to a simple handle comparison. I don't
think this is right, though. If anybody has any suggestions, let me know.
*/
#if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0502
return GetThreadId((HANDLE)lhs) == GetThreadId((HANDLE)rhs);
#else
return lhs == rhs;
#endif
}
c89thrd_t c89thrd_current(void)
{
return (c89thrd_t)GetCurrentThread();
}
int c89thrd_sleep(const struct timespec* duration, struct timespec* remaining)
{
/*
Sleeping is annoyingly complicated in C11. Nothing crazy or anything, but it's not just a simple
millisecond sleep. These are the rules:
* On success, return 0
* When the sleep is interupted due to a signal, return -1
* When any other error occurs, return some other negative value.
* When the sleep is interupted, the `remaining` output parameter needs to be filled out with
the remaining time.
In order to detect a signal, we can use SleepEx(). This only has a resolution of 1 millisecond,
however (this is true for everything on Windows). SleepEx() will return WAIT_IO_COMPLETION if
some I/O completion event occurs. This is the best we'll get on Windows, I think.
In order to calculate the value to place into `remaining`, we need to get the time before sleeping
and then get the time after the sleeping. We'll then have enough information to calculate the
difference which will be our remining. This is only required when the `remaining` parameter is not
NULL. Unfortunately we cannot use timespec_get() here because it doesn't have good support with
MinGW. We'll instead use Windows' high resolution performance counter which is supported back to
Windows 2000.
*/
static LARGE_INTEGER frequency;
LARGE_INTEGER start;
DWORD sleepResult;
DWORD sleepMilliseconds;
if (duration == NULL) {
return c89thrd_error;
}
start.QuadPart = 0;
if (remaining != NULL) {
if (frequency.QuadPart == 0) {
if (QueryPerformanceFrequency(&frequency) == FALSE) {
frequency.QuadPart = 0; /* Just to be sure... */
return c89thrd_error;
}
}
if (QueryPerformanceCounter(&start) == FALSE) {
return c89thrd_error; /* Failed to retrieve the start time. */
}
}
sleepMilliseconds = (DWORD)((duration->tv_sec * 1000) + (duration->tv_nsec / 1000000));
/*
A small, but important detail here. The C11 spec states that thrd_sleep() should sleep for a
*minimum* of the specified duration. In the above calculation we converted nanoseconds to
milliseconds, however this requires a division which may truncate a non-zero sub-millisecond
amount of time. We need to add an extra millisecond to meet the minimum duration requirement if
indeed we truncated.
*/
if ((duration->tv_nsec % 1000000) != 0) {
sleepMilliseconds += 1; /* We truncated a sub-millisecond amount of time. Add an extra millisecond to meet the minimum duration requirement. */
}
sleepResult = SleepEx(sleepMilliseconds, TRUE); /* <-- Make this sleep alertable so we can detect WAIT_IO_COMPLETION and return -1. */
if (sleepResult == 0) {
if (remaining != NULL) {
remaining->tv_sec = 0;
remaining->tv_nsec = 0;
}
return c89thrd_success;
}
/*
Getting here means we didn't sleep for the specified amount of time. We need to fill `remaining`.
To do this, we need to find out out much time has elapsed and then offset that will the requested
duration. This is the hard part of the process because we need to convert to and from timespec.
*/
if (remaining != NULL) {
LARGE_INTEGER end;
if (QueryPerformanceCounter(&end)) {
LARGE_INTEGER elapsed;
elapsed.QuadPart = end.QuadPart - start.QuadPart;
/*
The remaining amount of time is the requested duration, minus the elapsed time. This section warrents an explanation.
The section below is converting between our performance counters and timespec structures. Just above we calculated the
amount of the time that has elapsed since sleeping. By subtracting the requested duration from the elapsed duration,
we'll be left with the remaining duration.
The first thing we do is convert the requested duration to a LARGE_INTEGER which will be based on the performance counter
frequency we retrieved earlier. The Windows high performance counters are based on seconds, so a counter divided by the
frequency will give you the representation in seconds. By multiplying the counter by 1000 before the division by the
frequency you'll have a result in milliseconds, etc.
Once the remainder has be calculated based on the high performance counters, it's converted to the timespec structure
which is just the reverse.
*/
{
LARGE_INTEGER durationCounter;
LARGE_INTEGER remainingCounter;
durationCounter.QuadPart = ((duration->tv_sec * frequency.QuadPart) + ((duration->tv_nsec * frequency.QuadPart) / 1000000000));
if (durationCounter.QuadPart > elapsed.QuadPart) {
remainingCounter.QuadPart = durationCounter.QuadPart - elapsed.QuadPart;
} else {
remainingCounter.QuadPart = 0; /* For safety. Ensures we don't go negative. */
}
remaining->tv_sec = (time_t)((remainingCounter.QuadPart * 1) / frequency.QuadPart);
remaining->tv_nsec = (long)(((remainingCounter.QuadPart * 1000000000) / frequency.QuadPart) - (remaining->tv_sec * (LONGLONG)1000000000));
}
} else {
remaining->tv_sec = 0; /* Just for safety. */
remaining->tv_nsec = 0;
}
}
if (sleepResult == WAIT_IO_COMPLETION) {
return c89thrd_signal; /* -1 */
} else {
return c89thrd_error; /* "other negative value if an error occurred." */
}
}
void c89thrd_yield(void)
{
Sleep(0);
}
void c89thrd_exit(int res)
{
ExitThread((DWORD)res);
}
int c89thrd_detach(c89thrd_t thr)
{
/*
The documentation for thrd_detach() says explicitly that any error should return thrd_error.
We'll do the same, so make sure c89thrd_result_from_GetLastError() is not used here.
*/
BOOL result;
result = CloseHandle((HANDLE)thr);
if (!result) {
return c89thrd_error;
}
return c89thrd_success;
}
int c89thrd_join(c89thrd_t thr, int* res)
{
/*
Like thrd_detach(), the documentation for thrd_join() says to return thrd_success or thrd_error.
Therefore, make sure c89thrd_result_from_GetLastError() is not used here.
In Win32, waiting for the thread to complete and retrieving the result is done as two separate
steps.
*/
/* Wait for the thread. */
if (WaitForSingleObject((HANDLE)thr, INFINITE) == WAIT_FAILED) {
return c89thrd_error; /* Wait failed. */
}
/* Retrieve the result code if required. */
if (res != NULL) {
DWORD exitCode;
if (GetExitCodeThread((HANDLE)thr, &exitCode) == FALSE) {
return c89thrd_error;
}
*res = (int)exitCode;
}
/*
It's not entirely clear from the documentation for thrd_join() as to whether or not the thread
handle should be closed at this point. I think it makes sense to close it here, as I don't recall
ever seeing a pattern or joining a thread, and then explicitly closing the thread handle. I think
joining should be an implicit detach.
*/
return c89thrd_detach(thr);
}
int c89mtx_init(c89mtx_t* mutex, int type)
{
HANDLE hMutex;
if (mutex == NULL) {
return c89thrd_error;
}
/* Initialize the object to zero for safety. */
mutex->handle = NULL;
mutex->type = 0;
/*
CreateMutex() will create a thread-aware mutex (allowing recursiveness), whereas an auto-reset
event (CreateEvent()) is not thread-aware and will deadlock (will not allow recursiveness). In
Win32 I'm making all mutex's timeable.
*/
if ((type & c89mtx_recursive) != 0) {
hMutex = CreateMutex(NULL, FALSE, NULL);
} else {
hMutex = CreateEvent(NULL, FALSE, TRUE, NULL);
}
if (hMutex == NULL) {
return c89thrd_result_from_GetLastError(GetLastError());
}
mutex->handle = (c89thread_handle)hMutex;
mutex->type = type;
return c89thrd_success;
}
void c89mtx_destroy(c89mtx_t* mutex)
{
if (mutex == NULL) {
return;
}
CloseHandle((HANDLE)mutex->handle);
}
int c89mtx_lock(c89mtx_t* mutex)
{
DWORD result;
if (mutex == NULL) {
return c89thrd_error;
}
result = WaitForSingleObject((HANDLE)mutex->handle, INFINITE);
if (result != WAIT_OBJECT_0) {
return c89thrd_error;
}
return c89thrd_success;
}
int c89mtx_timedlock(c89mtx_t* mutex, const struct timespec* time_point)
{
DWORD result;
if (mutex == NULL || time_point == NULL) {
return c89thrd_error;
}
result = WaitForSingleObject((HANDLE)mutex->handle, (DWORD)c89timespec_diff_milliseconds(*time_point, c89timespec_now()));
if (result != WAIT_OBJECT_0) {
if (result == WAIT_TIMEOUT) {
return c89thrd_timedout;
}
return c89thrd_error;
}
return c89thrd_success;
}
int c89mtx_trylock(c89mtx_t* mutex)
{
DWORD result;
if (mutex == NULL) {
return c89thrd_error;
}
result = WaitForSingleObject((HANDLE)mutex->handle, 0);
if (result != WAIT_OBJECT_0) {
return c89thrd_busy;
}
return c89thrd_success;
}
int c89mtx_unlock(c89mtx_t* mutex)
{
BOOL result;
if (mutex == NULL) {
return c89thrd_error;
}
if ((mutex->type & c89mtx_recursive) != 0) {
result = ReleaseMutex((HANDLE)mutex->handle);
} else {
result = SetEvent((HANDLE)mutex->handle);
}
if (!result) {
return c89thrd_error;
}
return c89thrd_success;
}
int c89cnd_init(c89cnd_t* cnd)
{
if (cnd == NULL) {
return c89thrd_error;
}
/* Not supporting condition variables on Win32. */
return c89thrd_error;
}
void c89cnd_destroy(c89cnd_t* cnd)
{
if (cnd == NULL) {
return;
}
/* Not supporting condition variables on Win32. */
}
int c89cnd_signal(c89cnd_t* cnd)
{
if (cnd == NULL) {
return c89thrd_error;
}
/* Not supporting condition variables on Win32. */
return c89thrd_error;
}
int c89cnd_broadcast(c89cnd_t* cnd)
{
if (cnd == NULL) {
return c89thrd_error;
}
/* Not supporting condition variables on Win32. */
return c89thrd_error;
}
int c89cnd_wait(c89cnd_t* cnd, c89mtx_t* mtx)
{
if (cnd == NULL) {
return c89thrd_error;
}
(void)mtx;
/* Not supporting condition variables on Win32. */
return c89thrd_error;
}
int c89cnd_timedwait(c89cnd_t* cnd, c89mtx_t* mtx, const struct timespec* time_point)
{
if (cnd == NULL) {
return c89thrd_error;
}
(void)mtx;
(void)time_point;
/* Not supporting condition variables on Win32. */
return c89thrd_error;
}
int c89sem_init(c89sem_t* sem, int value, int valueMax)
{
HANDLE hSemaphore;
if (sem == NULL || valueMax == 0 || value > valueMax) {
return c89thrd_error;
}
*sem = NULL;
hSemaphore = CreateSemaphore(NULL, value, valueMax, NULL);
if (hSemaphore == NULL) {
return c89thrd_error;
}
*sem = hSemaphore;
return c89thrd_success;
}
void c89sem_destroy(c89sem_t* sem)
{
if (sem == NULL) {
return;
}
CloseHandle((HANDLE)*sem);
}
int c89sem_wait(c89sem_t* sem)
{
DWORD result;
if (sem == NULL) {
return c89thrd_error;
}
result = WaitForSingleObject((HANDLE)*sem, INFINITE);
if (result != WAIT_OBJECT_0) {
return c89thrd_error;
}
return c89thrd_success;
}
int c89sem_timedwait(c89sem_t* sem, const struct timespec* time_point)
{
DWORD result;
if (sem == NULL) {
return c89thrd_error;
}
result = WaitForSingleObject((HANDLE)*sem, (DWORD)c89timespec_diff_milliseconds(*time_point, c89timespec_now()));
if (result != WAIT_OBJECT_0) {
if (result == WAIT_TIMEOUT) {
return c89thrd_timedout;
}
return c89thrd_error;
}
return c89thrd_success;
}
int c89sem_post(c89sem_t* sem)
{
BOOL result;
if (sem == NULL) {
return c89thrd_error;
}
result = ReleaseSemaphore((HANDLE)*sem, 1, NULL);
if (!result) {
return c89thrd_error;
}
return c89thrd_success;
}
int c89evnt_init(c89evnt_t* evnt)
{
HANDLE hEvent;
if (evnt == NULL) {
return c89thrd_error;
}
*evnt = NULL;
hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (hEvent == NULL) {
return c89thrd_error;
}
*evnt = hEvent;
return c89thrd_success;
}
void c89evnt_destroy(c89evnt_t* evnt)
{
if (evnt == NULL) {
return;
}
CloseHandle((HANDLE)*evnt);
}
int c89evnt_wait(c89evnt_t* evnt)
{
DWORD result;
if (evnt == NULL) {
return c89thrd_error;
}
result = WaitForSingleObject((HANDLE)*evnt, INFINITE);
if (result != WAIT_OBJECT_0) {
return c89thrd_error;
}
return c89thrd_success;
}
int c89evnt_timedwait(c89evnt_t* evnt, const struct timespec* time_point)
{
DWORD result;
if (evnt == NULL) {
return c89thrd_error;
}
result = WaitForSingleObject((HANDLE)*evnt, (DWORD)c89timespec_diff_milliseconds(*time_point, c89timespec_now()));
if (result != WAIT_OBJECT_0) {
if (result == WAIT_TIMEOUT) {
return c89thrd_timedout;
}
return c89thrd_error;
}
return c89thrd_success;
}
int c89evnt_signal(c89evnt_t* evnt)
{
BOOL result;
if (evnt == NULL) {
return c89thrd_error;
}
result = SetEvent((HANDLE)*evnt);
if (!result) {
return c89thrd_error;
}
return c89thrd_success;
}
#endif
/* POSIX */
#if defined(C89THREAD_POSIX)
#include <pthread.h>
#include <stdlib.h> /* For malloc(), realloc(), free(). */
#include <errno.h> /* For errno_t. */
#include <sys/time.h> /* For timeval. */
#ifndef C89THREAD_MALLOC
#define C89THREAD_MALLOC(sz) malloc(sz)
#endif
#ifndef C89THREAD_REALLOC
#define C89THREAD_REALLOC(p, sz) realloc(p, sz)
#endif
#ifndef C89THREAD_FREE
#define C89THREAD_FREE(p) free(p)
#endif
static int c89thrd_result_from_errno(int e)
{
switch (e)
{
case 0: return c89thrd_success;
case ENOMEM: return c89thrd_nomem;
case ETIME: return c89thrd_timedout;
case ETIMEDOUT: return c89thrd_timedout;
case EBUSY: return c89thrd_busy;
}
return c89thrd_error;
}
typedef struct
{
c89thrd_start_t func;
void* arg;
c89thread_entry_exit_callbacks entryExitCallbacks;
c89thread_allocation_callbacks allocationCallbacks;
int usingCustomAllocator;
} c89thrd_start_data_posix;
static void* c89thrd_start_posix(void* pUserData)
{
c89thrd_start_data_posix* pStartData = (c89thrd_start_data_posix*)pUserData;
c89thread_entry_exit_callbacks entryExitCallbacks;
c89thrd_start_t func;
void* arg;
void* result;
entryExitCallbacks = pStartData->entryExitCallbacks;
if (entryExitCallbacks.onEntry != NULL) {
entryExitCallbacks.onEntry(entryExitCallbacks.pUserData);
}
/* Make sure we make a copy of the start data here. That way we can free pStartData straight away (it was allocated in c89thrd_create()). */
func = pStartData->func;
arg = pStartData->arg;
/* We should free the data pointer before entering into the start function. That way when c89thrd_exit() is called we don't leak. */
c89thread_free(pStartData, (pStartData->usingCustomAllocator) ? NULL : &pStartData->allocationCallbacks);
result = (void*)(c89thread_intptr)func(arg);
if (entryExitCallbacks.onExit != NULL) {
entryExitCallbacks.onExit(entryExitCallbacks.pUserData);
}
return result;
}
int c89thrd_create_ex(c89thrd_t* thr, c89thrd_start_t func, void* arg, const c89thread_entry_exit_callbacks* pEntryExitCallbacks, const c89thread_allocation_callbacks* pAllocationCallbacks)
{
int result;
c89thrd_start_data_posix* pData;
pthread_t thread;
if (thr == NULL) {
return c89thrd_error;
}
*thr = 0; /* Safety. */
if (func == NULL) {
return c89thrd_error;
}
pData = (c89thrd_start_data_posix*)c89thread_malloc(sizeof(*pData), pAllocationCallbacks); /* <-- This will be freed when c89thrd_start_posix() is entered. */
if (pData == NULL) {
return c89thrd_nomem;
}
pData->func = func;
pData->arg = arg;
if (pEntryExitCallbacks != NULL) {
pData->entryExitCallbacks = *pEntryExitCallbacks;
} else {
pData->entryExitCallbacks.onEntry = NULL;
pData->entryExitCallbacks.onExit = NULL;
pData->entryExitCallbacks.pUserData = NULL;
}
if (pAllocationCallbacks != NULL) {
pData->allocationCallbacks = *pAllocationCallbacks;
pData->usingCustomAllocator = 1;
} else {
pData->allocationCallbacks.onMalloc = NULL;
pData->allocationCallbacks.onRealloc = NULL;
pData->allocationCallbacks.onFree = NULL;
pData->allocationCallbacks.pUserData = NULL;
pData->usingCustomAllocator = 0;
}
result = pthread_create(&thread, NULL, c89thrd_start_posix, pData);
if (result != 0) {
c89thread_free(pData, pAllocationCallbacks);
return c89thrd_result_from_errno(errno);
}
*thr = thread;
return c89thrd_success;
}
int c89thrd_create(c89thrd_t* thr, c89thrd_start_t func, void* arg)
{
return c89thrd_create_ex(thr, func, arg, NULL, NULL);
}
int c89thrd_equal(c89thrd_t lhs, c89thrd_t rhs)
{
return pthread_equal(lhs, rhs);
}
c89thrd_t c89thrd_current(void)
{
return pthread_self();
}
int c89thrd_sleep(const struct timespec* duration, struct timespec* remaining)
{
/*
The documentation for thrd_sleep() mentions nanosleep(), so we'll go ahead and use that if it's
available. Otherwise we'll fallback to select() and use a similar algorithm to what we use with
the Windows build. We need to keep in mind the requirement to handle signal interrupts.
*/
int result;
#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309L
result = nanosleep(duration, remaining);
if (result != 0) {
if (result == EINTR) {
return c89thrd_signal;
}
return c89thrd_error;
}
#else
/*
We need to fall back to select(). We'll use c89timespec_get() to retrieve the time before and after
for the purpose of diffing.
*/
struct timeval tv;
struct timespec tsBeg;
struct timespec tsEnd;
if (duration == NULL) {
return c89thrd_error;
}
/*
We need to grab the time before the wait. This will be diff'd with the time after waiting to
produce the remaining amount.
*/
if (remaining != NULL) {
result = c89timespec_get(&tsBeg, TIME_UTC);
if (result == 0) {
return c89thrd_error; /* Failed to retrieve the start time. */
}
}
tv.tv_sec = duration->tv_sec;
tv.tv_usec = duration->tv_nsec / 1000;
/*
We need to sleep for the *minimum* of `duration`. Our nanoseconds-to-microseconds conversion
above may have truncated some nanoseconds, so we'll need to add a microsecond to compensate.
*/
if ((duration->tv_nsec % 1000) != 0) {
tv.tv_usec += 1;
if (tv.tv_usec > 1000000) {
tv.tv_usec = 0;
tv.tv_sec += 1;
}
}
result = select(0, NULL, NULL, NULL, &tv);
if (result == 0) {
if (remaining != NULL) {
remaining->tv_sec = 0;
remaining->tv_nsec = 0;
}
return c89thrd_success;
}
/* Getting here means didn't wait the whole time. We'll need to grab the diff. */
if (remaining != NULL) {
if (c89timespec_get(&tsEnd, TIME_UTC) != 0) {
*remaining = c89timespec_diff(tsEnd, tsBeg);
} else {
/* Failed to get the end time, somehow. Shouldn't ever happen. */
remaining->tv_sec = 0;
remaining->tv_nsec = 0;
}
}
if (result == EINTR) {
return c89thrd_signal;
} else {
return c89thrd_error;
}
#endif
return c89thrd_success;
}
void c89thrd_yield(void)
{
sched_yield();
}
void c89thrd_exit(int res)
{
pthread_exit((void*)(c89thread_intptr)res);
}
int c89thrd_detach(c89thrd_t thr)
{
/*
The documentation for thrd_detach() explicitly says c89thrd_success if successful or c89thrd_error
for any other error. Don't use c89thrd_result_from_errno() here.
*/
int result = pthread_detach(thr);
if (result != 0) {
return c89thrd_error;
}
return c89thrd_success;
}
int c89thrd_join(c89thrd_t thr, int* res)
{
/* Same rules apply here as thrd_detach() with respect to the return value. */
void* retval;
int result = pthread_join(thr, &retval);
if (result != 0) {
return c89thrd_error;
}
if (res != NULL) {
*res = (int)(c89thread_intptr)retval;
}
return c89thrd_success;
}
int c89mtx_init(c89mtx_t* mutex, int type)
{
int result;
pthread_mutexattr_t attr; /* For specifying whether or not the mutex is recursive. */
if (mutex == NULL) {
return c89thrd_error;
}
pthread_mutexattr_init(&attr);
if ((type & c89mtx_recursive) != 0) {
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
} else {
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL); /* Will deadlock. Consistent with Win32. */
}
result = pthread_mutex_init((pthread_mutex_t*)mutex, &attr);
pthread_mutexattr_destroy(&attr);
if (result != 0) {
return c89thrd_error;
}