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