1 /* Copyright (C) 2010-2020 The RetroArch team
2 *
3 * ---------------------------------------------------------------------------------------
4 * The following license statement only applies to this file (rthreads.c).
5 * ---------------------------------------------------------------------------------------
6 *
7 * Permission is hereby granted, free of charge,
8 * to any person obtaining a copy of this software and associated documentation files (the "Software"),
9 * to deal in the Software without restriction, including without limitation the rights to
10 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
11 * and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
16 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
19 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 */
22
23 #ifdef __unix__
24 #ifndef __sun__
25 #define _POSIX_C_SOURCE 199309
26 #endif
27 #endif
28
29 #include <stdlib.h>
30 #include <string.h>
31
32 #include <boolean.h>
33 #include <rthreads/rthreads.h>
34
35 /* with RETRO_WIN32_USE_PTHREADS, pthreads can be used even on win32. Maybe only supported in MSVC>=2005 */
36
37 #if defined(_WIN32) && !defined(RETRO_WIN32_USE_PTHREADS)
38 #define USE_WIN32_THREADS
39 #ifdef _XBOX
40 #include <xtl.h>
41 #else
42 #define WIN32_LEAN_AND_MEAN
43 #ifndef _WIN32_WINNT
44 #define _WIN32_WINNT 0x0500 /*_WIN32_WINNT_WIN2K */
45 #endif
46 #include <windows.h>
47 #include <mmsystem.h>
48 #endif
49 #elif defined(GEKKO)
50 #include "gx_pthread.h"
51 #elif defined(_3DS)
52 #include "ctr_pthread.h"
53 #else
54 #include <pthread.h>
55 #include <time.h>
56 #endif
57
58 #if defined(VITA) || defined(BSD) || defined(ORBIS)
59 #include <sys/time.h>
60 #endif
61
62 #ifdef __MACH__
63 #include <mach/clock.h>
64 #include <mach/mach.h>
65 #endif
66
67 struct thread_data
68 {
69 void (*func)(void*);
70 void *userdata;
71 };
72
73 struct sthread
74 {
75 #ifdef USE_WIN32_THREADS
76 HANDLE thread;
77 DWORD id;
78 #else
79 pthread_t id;
80 #endif
81 };
82
83 struct slock
84 {
85 #ifdef USE_WIN32_THREADS
86 CRITICAL_SECTION lock;
87 #else
88 pthread_mutex_t lock;
89 #endif
90 };
91
92 #ifdef USE_WIN32_THREADS
93 /* The syntax we'll use is mind-bending unless we use a struct. Plus, we might want to store more info later */
94 /* This will be used as a linked list immplementing a queue of waiting threads */
95 struct queue_entry
96 {
97 struct queue_entry *next;
98 };
99 #endif
100
101 struct scond
102 {
103 #ifdef USE_WIN32_THREADS
104 /* With this implementation of scond, we don't have any way of waking
105 * (or even identifying) specific threads
106 * But we need to wake them in the order indicated by the queue.
107 * This potato token will get get passed around every waiter.
108 * The bearer can test whether he's next, and hold onto the potato if he is.
109 * When he's done he can then put it back into play to progress
110 * the queue further */
111 HANDLE hot_potato;
112
113 /* The primary signalled event. Hot potatoes are passed until this is set. */
114 HANDLE event;
115
116 /* the head of the queue; NULL if queue is empty */
117 struct queue_entry *head;
118
119 /* equivalent to the queue length */
120 int waiters;
121
122 /* how many waiters in the queue have been conceptually wakened by signals
123 * (even if we haven't managed to actually wake them yet) */
124 int wakens;
125
126 /* used to control access to this scond, in case the user fails */
127 CRITICAL_SECTION cs;
128
129 #else
130 pthread_cond_t cond;
131 #endif
132 };
133
134 #ifdef USE_WIN32_THREADS
thread_wrap(void * data_)135 static DWORD CALLBACK thread_wrap(void *data_)
136 #else
137 static void *thread_wrap(void *data_)
138 #endif
139 {
140 struct thread_data *data = (struct thread_data*)data_;
141 if (!data)
142 return 0;
143 data->func(data->userdata);
144 free(data);
145 return 0;
146 }
147
148 /**
149 * sthread_create:
150 * @start_routine : thread entry callback function
151 * @userdata : pointer to userdata that will be made
152 * available in thread entry callback function
153 *
154 * Create a new thread.
155 *
156 * Returns: pointer to new thread if successful, otherwise NULL.
157 */
sthread_create(void (* thread_func)(void *),void * userdata)158 sthread_t *sthread_create(void (*thread_func)(void*), void *userdata)
159 {
160 return sthread_create_with_priority(thread_func, userdata, 0);
161 }
162
163 /* TODO/FIXME - this needs to be implemented for Switch/3DS */
164 #if !defined(SWITCH) && !defined(USE_WIN32_THREADS) && !defined(_3DS) && !defined(GEKKO) && !defined(__HAIKU__) && !defined(EMSCRIPTEN)
165 #define HAVE_THREAD_ATTR
166 #endif
167
168 /**
169 * sthread_create_with_priority:
170 * @start_routine : thread entry callback function
171 * @userdata : pointer to userdata that will be made
172 * available in thread entry callback function
173 * @thread_priority : thread priority hint value from [1-100]
174 *
175 * Create a new thread. It is possible for the caller to give a hint
176 * for the thread's priority from [1-100]. Any passed in @thread_priority
177 * values that are outside of this range will cause sthread_create() to
178 * create a new thread using the operating system's default thread
179 * priority.
180 *
181 * Returns: pointer to new thread if successful, otherwise NULL.
182 */
sthread_create_with_priority(void (* thread_func)(void *),void * userdata,int thread_priority)183 sthread_t *sthread_create_with_priority(void (*thread_func)(void*), void *userdata, int thread_priority)
184 {
185 #ifdef HAVE_THREAD_ATTR
186 pthread_attr_t thread_attr;
187 bool thread_attr_needed = false;
188 #endif
189 bool thread_created = false;
190 struct thread_data *data = NULL;
191 sthread_t *thread = (sthread_t*)malloc(sizeof(*thread));
192
193 if (!thread)
194 return NULL;
195
196 data = (struct thread_data*)malloc(sizeof(*data));
197 if (!data)
198 goto error;
199
200 data->func = thread_func;
201 data->userdata = userdata;
202
203 #ifdef USE_WIN32_THREADS
204 thread->id = 0;
205 thread->thread = CreateThread(NULL, 0, thread_wrap,
206 data, 0, &thread->id);
207 thread_created = !!thread->thread;
208 #else
209 thread->id = 0;
210
211 #ifdef HAVE_THREAD_ATTR
212 pthread_attr_init(&thread_attr);
213
214 if ((thread_priority >= 1) && (thread_priority <= 100))
215 {
216 struct sched_param sp;
217 memset(&sp, 0, sizeof(struct sched_param));
218 sp.sched_priority = thread_priority;
219 pthread_attr_setschedpolicy(&thread_attr, SCHED_RR);
220 pthread_attr_setschedparam(&thread_attr, &sp);
221
222 thread_attr_needed = true;
223 }
224 #endif
225
226 #if defined(VITA)
227 pthread_attr_setstacksize(&thread_attr , 0x10000 );
228 thread_attr_needed = true;
229 #endif
230
231 #ifdef HAVE_THREAD_ATTR
232 if (thread_attr_needed)
233 thread_created = pthread_create(&thread->id, &thread_attr, thread_wrap, data) == 0;
234 else
235 #endif
236 thread_created = pthread_create(&thread->id, NULL, thread_wrap, data) == 0;
237
238 #ifdef HAVE_THREAD_ATTR
239 pthread_attr_destroy(&thread_attr);
240 #endif
241 #endif
242
243 if (thread_created)
244 return thread;
245
246 error:
247 if (data)
248 free(data);
249 free(thread);
250 return NULL;
251 }
252
253 /**
254 * sthread_detach:
255 * @thread : pointer to thread object
256 *
257 * Detach a thread. When a detached thread terminates, its
258 * resources are automatically released back to the system
259 * without the need for another thread to join with the
260 * terminated thread.
261 *
262 * Returns: 0 on success, otherwise it returns a non-zero error number.
263 */
sthread_detach(sthread_t * thread)264 int sthread_detach(sthread_t *thread)
265 {
266 #ifdef USE_WIN32_THREADS
267 CloseHandle(thread->thread);
268 free(thread);
269 return 0;
270 #else
271 int ret = pthread_detach(thread->id);
272 free(thread);
273 return ret;
274 #endif
275 }
276
277 /**
278 * sthread_join:
279 * @thread : pointer to thread object
280 *
281 * Join with a terminated thread. Waits for the thread specified by
282 * @thread to terminate. If that thread has already terminated, then
283 * it will return immediately. The thread specified by @thread must
284 * be joinable.
285 *
286 * Returns: 0 on success, otherwise it returns a non-zero error number.
287 */
sthread_join(sthread_t * thread)288 void sthread_join(sthread_t *thread)
289 {
290 if (!thread)
291 return;
292 #ifdef USE_WIN32_THREADS
293 WaitForSingleObject(thread->thread, INFINITE);
294 CloseHandle(thread->thread);
295 #else
296 pthread_join(thread->id, NULL);
297 #endif
298 free(thread);
299 }
300
301 /**
302 * sthread_isself:
303 * @thread : pointer to thread object
304 *
305 * Returns: true (1) if calling thread is the specified thread
306 */
sthread_isself(sthread_t * thread)307 bool sthread_isself(sthread_t *thread)
308 {
309 /* This thread can't possibly be a null thread */
310 if (!thread)
311 return false;
312
313 #ifdef USE_WIN32_THREADS
314 return GetCurrentThreadId() == thread->id;
315 #else
316 return pthread_equal(pthread_self(),thread->id);
317 #endif
318 }
319
320 /**
321 * slock_new:
322 *
323 * Create and initialize a new mutex. Must be manually
324 * freed.
325 *
326 * Returns: pointer to a new mutex if successful, otherwise NULL.
327 **/
slock_new(void)328 slock_t *slock_new(void)
329 {
330 bool mutex_created = false;
331 slock_t *lock = (slock_t*)calloc(1, sizeof(*lock));
332 if (!lock)
333 return NULL;
334
335
336 #ifdef USE_WIN32_THREADS
337 InitializeCriticalSection(&lock->lock);
338 mutex_created = true;
339 #else
340 mutex_created = (pthread_mutex_init(&lock->lock, NULL) == 0);
341 #endif
342
343 if (!mutex_created)
344 goto error;
345
346 return lock;
347
348 error:
349 free(lock);
350 return NULL;
351 }
352
353 /**
354 * slock_free:
355 * @lock : pointer to mutex object
356 *
357 * Frees a mutex.
358 **/
slock_free(slock_t * lock)359 void slock_free(slock_t *lock)
360 {
361 if (!lock)
362 return;
363
364 #ifdef USE_WIN32_THREADS
365 DeleteCriticalSection(&lock->lock);
366 #else
367 pthread_mutex_destroy(&lock->lock);
368 #endif
369 free(lock);
370 }
371
372 /**
373 * slock_lock:
374 * @lock : pointer to mutex object
375 *
376 * Locks a mutex. If a mutex is already locked by
377 * another thread, the calling thread shall block until
378 * the mutex becomes available.
379 **/
slock_lock(slock_t * lock)380 void slock_lock(slock_t *lock)
381 {
382 if (!lock)
383 return;
384 #ifdef USE_WIN32_THREADS
385 EnterCriticalSection(&lock->lock);
386 #else
387 pthread_mutex_lock(&lock->lock);
388 #endif
389 }
390
391 /**
392 * slock_try_lock:
393 * @lock : pointer to mutex object
394 *
395 * Attempts to lock a mutex. If a mutex is already locked by
396 * another thread, return false. If the lock is acquired, return true.
397 **/
slock_try_lock(slock_t * lock)398 bool slock_try_lock(slock_t *lock)
399 {
400 if (!lock)
401 return false;
402 #ifdef USE_WIN32_THREADS
403 return TryEnterCriticalSection(&lock->lock);
404 #else
405 return pthread_mutex_trylock(&lock->lock)==0;
406 #endif
407 }
408
409 /**
410 * slock_unlock:
411 * @lock : pointer to mutex object
412 *
413 * Unlocks a mutex.
414 **/
slock_unlock(slock_t * lock)415 void slock_unlock(slock_t *lock)
416 {
417 if (!lock)
418 return;
419 #ifdef USE_WIN32_THREADS
420 LeaveCriticalSection(&lock->lock);
421 #else
422 pthread_mutex_unlock(&lock->lock);
423 #endif
424 }
425
426 /**
427 * scond_new:
428 *
429 * Creates and initializes a condition variable. Must
430 * be manually freed.
431 *
432 * Returns: pointer to new condition variable on success,
433 * otherwise NULL.
434 **/
scond_new(void)435 scond_t *scond_new(void)
436 {
437 scond_t *cond = (scond_t*)calloc(1, sizeof(*cond));
438
439 if (!cond)
440 return NULL;
441
442 #ifdef USE_WIN32_THREADS
443 /* This is very complex because recreating condition variable semantics
444 * with Win32 parts is not easy.
445 *
446 * The main problem is that a condition variable can't be used to
447 * "pre-wake" a thread (it will get wakened only after it's waited).
448 *
449 * Whereas a win32 event can pre-wake a thread (the event will be set
450 * in advance, so a 'waiter' won't even have to wait on it).
451 *
452 * Keep in mind a condition variable can apparently pre-wake a thread,
453 * insofar as spurious wakeups are always possible,
454 * but nobody will be expecting this and it does not need to be simulated.
455 *
456 * Moreover, we won't be doing this, because it counts as a spurious wakeup
457 * -- someone else with a genuine claim must get wakened, in any case.
458 *
459 * Therefore we choose to wake only one of the correct waiting threads.
460 * So at the very least, we need to do something clever. But there's
461 * bigger problems.
462 * We don't even have a straightforward way in win32 to satisfy
463 * pthread_cond_wait's atomicity requirement. The bulk of this
464 * algorithm is solving that.
465 *
466 * Note: We might could simplify this using vista+ condition variables,
467 * but we wanted an XP compatible solution. */
468 cond->event = CreateEvent(NULL, FALSE, FALSE, NULL);
469 if (!cond->event)
470 goto error;
471 cond->hot_potato = CreateEvent(NULL, FALSE, FALSE, NULL);
472 if (!cond->hot_potato)
473 {
474 CloseHandle(cond->event);
475 goto error;
476 }
477
478 InitializeCriticalSection(&cond->cs);
479 #else
480 if (pthread_cond_init(&cond->cond, NULL) != 0)
481 goto error;
482 #endif
483
484 return cond;
485
486 error:
487 free(cond);
488 return NULL;
489 }
490
491 /**
492 * scond_free:
493 * @cond : pointer to condition variable object
494 *
495 * Frees a condition variable.
496 **/
scond_free(scond_t * cond)497 void scond_free(scond_t *cond)
498 {
499 if (!cond)
500 return;
501
502 #ifdef USE_WIN32_THREADS
503 CloseHandle(cond->event);
504 CloseHandle(cond->hot_potato);
505 DeleteCriticalSection(&cond->cs);
506 #else
507 pthread_cond_destroy(&cond->cond);
508 #endif
509 free(cond);
510 }
511
512 #ifdef USE_WIN32_THREADS
_scond_wait_win32(scond_t * cond,slock_t * lock,DWORD dwMilliseconds)513 static bool _scond_wait_win32(scond_t *cond, slock_t *lock, DWORD dwMilliseconds)
514 {
515 struct queue_entry myentry;
516 struct queue_entry **ptr;
517
518 #if _WIN32_WINNT >= 0x0500 || defined(_XBOX)
519 static LARGE_INTEGER performanceCounterFrequency;
520 LARGE_INTEGER tsBegin;
521 static bool first_init = true;
522 #else
523 static bool beginPeriod = false;
524 DWORD tsBegin;
525 #endif
526
527 DWORD waitResult;
528 DWORD dwFinalTimeout = dwMilliseconds; /* Careful! in case we begin in the head,
529 we don't do the hot potato stuff,
530 so this timeout needs presetting. */
531
532 /* Reminder: `lock` is held before this is called. */
533 /* however, someone else may have called scond_signal without the lock. soo... */
534 EnterCriticalSection(&cond->cs);
535
536 /* since this library is meant for realtime game software
537 * I have no problem setting this to 1 and forgetting about it. */
538 #if _WIN32_WINNT >= 0x0500 || defined(_XBOX)
539 if (first_init)
540 {
541 performanceCounterFrequency.QuadPart = 0;
542 first_init = false;
543 }
544
545 if (performanceCounterFrequency.QuadPart == 0)
546 {
547 QueryPerformanceFrequency(&performanceCounterFrequency);
548 }
549 #else
550 if (!beginPeriod)
551 {
552 beginPeriod = true;
553 timeBeginPeriod(1);
554 }
555 #endif
556
557 /* Now we can take a good timestamp for use in faking the timeout ourselves. */
558 /* But don't bother unless we need to (to save a little time) */
559 if (dwMilliseconds != INFINITE)
560 #if _WIN32_WINNT >= 0x0500 || defined(_XBOX)
561 QueryPerformanceCounter(&tsBegin);
562 #else
563 tsBegin = timeGetTime();
564 #endif
565
566 /* add ourselves to a queue of waiting threads */
567 ptr = &cond->head;
568
569 /* walk to the end of the linked list */
570 while (*ptr)
571 ptr = &((*ptr)->next);
572
573 *ptr = &myentry;
574 myentry.next = NULL;
575
576 cond->waiters++;
577
578 /* now the conceptual lock release and condition block are supposed to be atomic.
579 * we can't do that in Windows, but we can simulate the effects by using
580 * the queue, by the following analysis:
581 * What happens if they aren't atomic?
582 *
583 * 1. a signaller can rush in and signal, expecting a waiter to get it;
584 * but the waiter wouldn't, because he isn't blocked yet.
585 * Solution: Win32 events make this easy. The event will sit there enabled
586 *
587 * 2. a signaller can rush in and signal, and then turn right around and wait.
588 * Solution: the signaller will get queued behind the waiter, who's
589 * enqueued before he releases the mutex. */
590
591 /* It's my turn if I'm the head of the queue.
592 * Check to see if it's my turn. */
593 while (cond->head != &myentry)
594 {
595 /* It isn't my turn: */
596 DWORD timeout = INFINITE;
597
598 /* As long as someone is even going to be able to wake up
599 * when they receive the potato, keep it going round. */
600 if (cond->wakens > 0)
601 SetEvent(cond->hot_potato);
602
603 /* Assess the remaining timeout time */
604 if (dwMilliseconds != INFINITE)
605 {
606 #if _WIN32_WINNT >= 0x0500 || defined(_XBOX)
607 LARGE_INTEGER now;
608 LONGLONG elapsed;
609
610 QueryPerformanceCounter(&now);
611 elapsed = now.QuadPart - tsBegin.QuadPart;
612 elapsed *= 1000;
613 elapsed /= performanceCounterFrequency.QuadPart;
614 #else
615 DWORD now = timeGetTime();
616 DWORD elapsed = now - tsBegin;
617 #endif
618
619 /* Try one last time with a zero timeout (keeps the code simpler) */
620 if (elapsed > dwMilliseconds)
621 elapsed = dwMilliseconds;
622
623 timeout = dwMilliseconds - elapsed;
624 }
625
626 /* Let someone else go */
627 LeaveCriticalSection(&lock->lock);
628 LeaveCriticalSection(&cond->cs);
629
630 /* Wait a while to catch the hot potato..
631 * someone else should get a chance to go */
632 /* After all, it isn't my turn (and it must be someone else's) */
633 Sleep(0);
634 waitResult = WaitForSingleObject(cond->hot_potato, timeout);
635
636 /* I should come out of here with the main lock taken */
637 EnterCriticalSection(&lock->lock);
638 EnterCriticalSection(&cond->cs);
639
640 if (waitResult == WAIT_TIMEOUT)
641 {
642 /* Out of time! Now, let's think about this. I do have the potato now--
643 * maybe it's my turn, and I have the event?
644 * If that's the case, I could proceed right now without aborting
645 * due to timeout.
646 *
647 * However.. I DID wait a real long time. The caller was willing
648 * to wait that long.
649 *
650 * I choose to give him one last chance with a zero timeout
651 * in the next step
652 */
653 if (cond->head == &myentry)
654 {
655 dwFinalTimeout = 0;
656 break;
657 }
658 else
659 {
660 /* It's not our turn and we're out of time. Give up.
661 * Remove ourself from the queue and bail. */
662 struct queue_entry *curr = cond->head;
663
664 while (curr->next != &myentry)
665 curr = curr->next;
666 curr->next = myentry.next;
667 cond->waiters--;
668 LeaveCriticalSection(&cond->cs);
669 return false;
670 }
671 }
672
673 }
674
675 /* It's my turn now -- and I hold the potato */
676
677 /* I still have the main lock, in any case */
678 /* I need to release it so that someone can set the event */
679 LeaveCriticalSection(&lock->lock);
680 LeaveCriticalSection(&cond->cs);
681
682 /* Wait for someone to actually signal this condition */
683 /* We're the only waiter waiting on the event right now -- everyone else
684 * is waiting on something different */
685 waitResult = WaitForSingleObject(cond->event, dwFinalTimeout);
686
687 /* Take the main lock so we can do work. Nobody else waits on this lock
688 * for very long, so even though it's GO TIME we won't have to wait long */
689 EnterCriticalSection(&lock->lock);
690 EnterCriticalSection(&cond->cs);
691
692 /* Remove ourselves from the queue */
693 cond->head = myentry.next;
694 cond->waiters--;
695
696 if (waitResult == WAIT_TIMEOUT)
697 {
698 /* Oops! ran out of time in the final wait. Just bail. */
699 LeaveCriticalSection(&cond->cs);
700 return false;
701 }
702
703 /* If any other wakenings are pending, go ahead and set it up */
704 /* There may actually be no waiters. That's OK. The first waiter will come in,
705 * find it's his turn, and immediately get the signaled event */
706 cond->wakens--;
707 if (cond->wakens > 0)
708 {
709 SetEvent(cond->event);
710
711 /* Progress the queue: Put the hot potato back into play. It'll be
712 * tossed around until next in line gets it */
713 SetEvent(cond->hot_potato);
714 }
715
716 LeaveCriticalSection(&cond->cs);
717 return true;
718 }
719 #endif
720
721 /**
722 * scond_wait:
723 * @cond : pointer to condition variable object
724 * @lock : pointer to mutex object
725 *
726 * Block on a condition variable (i.e. wait on a condition).
727 **/
scond_wait(scond_t * cond,slock_t * lock)728 void scond_wait(scond_t *cond, slock_t *lock)
729 {
730 #ifdef USE_WIN32_THREADS
731 _scond_wait_win32(cond, lock, INFINITE);
732 #else
733 pthread_cond_wait(&cond->cond, &lock->lock);
734 #endif
735 }
736
737 /**
738 * scond_broadcast:
739 * @cond : pointer to condition variable object
740 *
741 * Broadcast a condition. Unblocks all threads currently blocked
742 * on the specified condition variable @cond.
743 **/
scond_broadcast(scond_t * cond)744 int scond_broadcast(scond_t *cond)
745 {
746 #ifdef USE_WIN32_THREADS
747 /* remember: we currently have mutex */
748 if (cond->waiters == 0)
749 return 0;
750
751 /* awaken everything which is currently queued up */
752 if (cond->wakens == 0)
753 SetEvent(cond->event);
754 cond->wakens = cond->waiters;
755
756 /* Since there is now at least one pending waken, the potato must be in play */
757 SetEvent(cond->hot_potato);
758
759 return 0;
760 #else
761 return pthread_cond_broadcast(&cond->cond);
762 #endif
763 }
764
765 /**
766 * scond_signal:
767 * @cond : pointer to condition variable object
768 *
769 * Signal a condition. Unblocks at least one of the threads currently blocked
770 * on the specified condition variable @cond.
771 **/
scond_signal(scond_t * cond)772 void scond_signal(scond_t *cond)
773 {
774 #ifdef USE_WIN32_THREADS
775
776 /* Unfortunately, pthread_cond_signal does not require that the
777 * lock be held in advance */
778 /* To avoid stomping on the condvar from other threads, we need
779 * to control access to it with this */
780 EnterCriticalSection(&cond->cs);
781
782 /* remember: we currently have mutex */
783 if (cond->waiters == 0)
784 {
785 LeaveCriticalSection(&cond->cs);
786 return;
787 }
788
789 /* wake up the next thing in the queue */
790 if (cond->wakens == 0)
791 SetEvent(cond->event);
792
793 cond->wakens++;
794
795 /* The data structure is done being modified.. I think we can leave the CS now.
796 * This would prevent some other thread from receiving the hot potato and then
797 * immediately stalling for the critical section.
798 * But remember, we were trying to replicate a semantic where this entire
799 * scond_signal call was controlled (by the user) by a lock.
800 * So in case there's trouble with this, we can move it after SetEvent() */
801 LeaveCriticalSection(&cond->cs);
802
803 /* Since there is now at least one pending waken, the potato must be in play */
804 SetEvent(cond->hot_potato);
805
806 #else
807 pthread_cond_signal(&cond->cond);
808 #endif
809 }
810
811 /**
812 * scond_wait_timeout:
813 * @cond : pointer to condition variable object
814 * @lock : pointer to mutex object
815 * @timeout_us : timeout (in microseconds)
816 *
817 * Try to block on a condition variable (i.e. wait on a condition) until
818 * @timeout_us elapses.
819 *
820 * Returns: false (0) if timeout elapses before condition variable is
821 * signaled or broadcast, otherwise true (1).
822 **/
scond_wait_timeout(scond_t * cond,slock_t * lock,int64_t timeout_us)823 bool scond_wait_timeout(scond_t *cond, slock_t *lock, int64_t timeout_us)
824 {
825 #ifdef USE_WIN32_THREADS
826 /* How to convert a microsecond (us) timeout to millisecond (ms)?
827 *
828 * Someone asking for a 0 timeout clearly wants immediate timeout.
829 * Someone asking for a 1 timeout clearly wants an actual timeout
830 * of the minimum length */
831
832 /* Someone asking for 1000 or 1001 timeout shouldn't
833 * accidentally get 2ms. */
834 DWORD dwMilliseconds = timeout_us/1000;
835
836 /* The implementation of a 0 timeout here with pthreads is sketchy.
837 * It isn't clear what happens if pthread_cond_timedwait is called with NOW.
838 * Moreover, it is possible that this thread gets pre-empted after the
839 * clock_gettime but before the pthread_cond_timedwait.
840 * In order to help smoke out problems caused by this strange usage,
841 * let's treat a 0 timeout as always timing out.
842 */
843 if (timeout_us == 0)
844 return false;
845 else if (timeout_us < 1000)
846 dwMilliseconds = 1;
847
848 return _scond_wait_win32(cond,lock,dwMilliseconds);
849 #else
850 int ret;
851 int64_t seconds, remainder;
852 struct timespec now = {0};
853
854 #ifdef __MACH__
855 /* OSX doesn't have clock_gettime. */
856 clock_serv_t cclock;
857 mach_timespec_t mts;
858
859 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
860 clock_get_time(cclock, &mts);
861 mach_port_deallocate(mach_task_self(), cclock);
862 now.tv_sec = mts.tv_sec;
863 now.tv_nsec = mts.tv_nsec;
864 #elif !defined(__PSL1GHT__) && defined(__PS3__)
865 sys_time_sec_t s;
866 sys_time_nsec_t n;
867
868 sys_time_get_current_time(&s, &n);
869 now.tv_sec = s;
870 now.tv_nsec = n;
871 #elif defined(PS2)
872 int tickms = ps2_clock();
873 now.tv_sec = tickms/1000;
874 now.tv_nsec = tickms * 1000;
875 #elif !defined(DINGUX_BETA) && (defined(__mips__) || defined(VITA) || defined(_3DS))
876 struct timeval tm;
877
878 gettimeofday(&tm, NULL);
879 now.tv_sec = tm.tv_sec;
880 now.tv_nsec = tm.tv_usec * 1000;
881 #elif defined(RETRO_WIN32_USE_PTHREADS)
882 _ftime64_s(&now);
883 #elif !defined(GEKKO)
884 /* timeout on libogc is duration, not end time. */
885 clock_gettime(CLOCK_REALTIME, &now);
886 #endif
887
888 seconds = timeout_us / INT64_C(1000000);
889 remainder = timeout_us % INT64_C(1000000);
890
891 now.tv_sec += seconds;
892 now.tv_nsec += remainder * INT64_C(1000);
893
894 if (now.tv_nsec > 1000000000)
895 {
896 now.tv_nsec -= 1000000000;
897 now.tv_sec += 1;
898 }
899
900 ret = pthread_cond_timedwait(&cond->cond, &lock->lock, &now);
901 return (ret == 0);
902 #endif
903 }
904
905 #ifdef HAVE_THREAD_STORAGE
sthread_tls_create(sthread_tls_t * tls)906 bool sthread_tls_create(sthread_tls_t *tls)
907 {
908 #ifdef USE_WIN32_THREADS
909 return (*tls = TlsAlloc()) != TLS_OUT_OF_INDEXES;
910 #else
911 return pthread_key_create((pthread_key_t*)tls, NULL) == 0;
912 #endif
913 }
914
sthread_tls_delete(sthread_tls_t * tls)915 bool sthread_tls_delete(sthread_tls_t *tls)
916 {
917 #ifdef USE_WIN32_THREADS
918 return TlsFree(*tls) != 0;
919 #else
920 return pthread_key_delete(*tls) == 0;
921 #endif
922 }
923
sthread_tls_get(sthread_tls_t * tls)924 void *sthread_tls_get(sthread_tls_t *tls)
925 {
926 #ifdef USE_WIN32_THREADS
927 return TlsGetValue(*tls);
928 #else
929 return pthread_getspecific(*tls);
930 #endif
931 }
932
sthread_tls_set(sthread_tls_t * tls,const void * data)933 bool sthread_tls_set(sthread_tls_t *tls, const void *data)
934 {
935 #ifdef USE_WIN32_THREADS
936 return TlsSetValue(*tls, (void*)data) != 0;
937 #else
938 return pthread_setspecific(*tls, data) == 0;
939 #endif
940 }
941 #endif
942
sthread_get_thread_id(sthread_t * thread)943 uintptr_t sthread_get_thread_id(sthread_t *thread)
944 {
945 if (!thread)
946 return 0;
947 return (uintptr_t)thread->id;
948 }
949
sthread_get_current_thread_id(void)950 uintptr_t sthread_get_current_thread_id(void)
951 {
952 #ifdef USE_WIN32_THREADS
953 return (uintptr_t)GetCurrentThreadId();
954 #else
955 return (uintptr_t)pthread_self();
956 #endif
957 }
958