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