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