summaryrefslogtreecommitdiffstats
path: root/libs/utils/Threads.cpp
blob: 74271ba3b41bcf7356a45c713c34b11c3a3afc10 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define LOG_TAG "libutils.threads"

#include <utils/threads.h>
#include <utils/Log.h>

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <errno.h>
#include <assert.h>
#include <unistd.h>

#if defined(HAVE_PTHREADS)
# include <pthread.h>
# include <sched.h>
# include <sys/resource.h>
#elif defined(HAVE_WIN32_THREADS)
# include <windows.h>
# include <stdint.h>
# include <process.h>
# define HAVE_CREATETHREAD  // Cygwin, vs. HAVE__BEGINTHREADEX for MinGW
#endif

#if defined(HAVE_FUTEX)
#include <private/utils/futex_synchro.h>
#endif

#if defined(HAVE_PRCTL)
#include <sys/prctl.h>
#endif

/*
 * ===========================================================================
 *      Thread wrappers
 * ===========================================================================
 */

using namespace android;

// ----------------------------------------------------------------------------
#if defined(HAVE_PTHREADS)
#if 0
#pragma mark -
#pragma mark PTHREAD
#endif
// ----------------------------------------------------------------------------

/*
 * Create and run a new thead.
 *
 * We create it "detached", so it cleans up after itself.
 */

typedef void* (*android_pthread_entry)(void*);

struct thread_data_t {
    thread_func_t   entryFunction;
    void*           userData;
    int             priority;
    char *          threadName;

    // we use this trampoline when we need to set the priority with
    // nice/setpriority.
    static int trampoline(const thread_data_t* t) {
        thread_func_t f = t->entryFunction;
        void* u = t->userData;
        int prio = t->priority;
        char * name = t->threadName;
        delete t;
        setpriority(PRIO_PROCESS, 0, prio);
        if (name) {
#if defined(HAVE_PRCTL)
            // Mac OS doesn't have this, and we build libutil for the host too
            int hasAt = 0;
            int hasDot = 0;
            char *s = name;
            while (*s) {
                if (*s == '.') hasDot = 1;
                else if (*s == '@') hasAt = 1;
                s++;
            }
            int len = s - name;
            if (len < 15 || hasAt || !hasDot) {
                s = name;
            } else {
                s = name + len - 15;
            }
            prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
#endif
            free(name);
        }
        return f(u);
    }
};

int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
                               void *userData,
                               const char* threadName,
                               int32_t threadPriority,
                               size_t threadStackSize,
                               android_thread_id_t *threadId)
{
    pthread_attr_t attr; 
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

#ifdef HAVE_ANDROID_OS  /* valgrind is rejecting RT-priority create reqs */
    if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
        // We could avoid the trampoline if there was a way to get to the
        // android_thread_id_t (pid) from pthread_t
        thread_data_t* t = new thread_data_t;
        t->priority = threadPriority;
        t->threadName = threadName ? strdup(threadName) : NULL;
        t->entryFunction = entryFunction;
        t->userData = userData;
        entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
        userData = t;            
    }
#endif

    if (threadStackSize) {
        pthread_attr_setstacksize(&attr, threadStackSize);
    }
    
    errno = 0;
    pthread_t thread;
    int result = pthread_create(&thread, &attr,
                    (android_pthread_entry)entryFunction, userData);
    if (result != 0) {
        LOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, errno=%d)\n"
             "(android threadPriority=%d)",
            entryFunction, result, errno, threadPriority);
        return 0;
    }

    if (threadId != NULL) {
        *threadId = (android_thread_id_t)thread; // XXX: this is not portable
    }
    return 1;
}

android_thread_id_t androidGetThreadId()
{
    return (android_thread_id_t)pthread_self();
}

// ----------------------------------------------------------------------------
#elif defined(HAVE_WIN32_THREADS)
#if 0
#pragma mark -
#pragma mark WIN32_THREADS
#endif
// ----------------------------------------------------------------------------

/*
 * Trampoline to make us __stdcall-compliant.
 *
 * We're expected to delete "vDetails" when we're done.
 */
struct threadDetails {
    int (*func)(void*);
    void* arg;
};
static __stdcall unsigned int threadIntermediary(void* vDetails)
{
    struct threadDetails* pDetails = (struct threadDetails*) vDetails;
    int result;

    result = (*(pDetails->func))(pDetails->arg);

    delete pDetails;

    LOG(LOG_VERBOSE, "thread", "thread exiting\n");
    return (unsigned int) result;
}

/*
 * Create and run a new thread.
 */
static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
{
    HANDLE hThread;
    struct threadDetails* pDetails = new threadDetails; // must be on heap
    unsigned int thrdaddr;

    pDetails->func = fn;
    pDetails->arg = arg;

#if defined(HAVE__BEGINTHREADEX)
    hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
                    &thrdaddr);
    if (hThread == 0)
#elif defined(HAVE_CREATETHREAD)
    hThread = CreateThread(NULL, 0,
                    (LPTHREAD_START_ROUTINE) threadIntermediary,
                    (void*) pDetails, 0, (DWORD*) &thrdaddr);
    if (hThread == NULL)
#endif
    {
        LOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
        return false;
    }

#if defined(HAVE_CREATETHREAD)
    /* close the management handle */
    CloseHandle(hThread);
#endif

    if (id != NULL) {
      	*id = (android_thread_id_t)thrdaddr;
    }

    return true;
}

int androidCreateRawThreadEtc(android_thread_func_t fn,
                               void *userData,
                               const char* threadName,
                               int32_t threadPriority,
                               size_t threadStackSize,
                               android_thread_id_t *threadId)
{
    return doCreateThread(  fn, userData, threadId);
}

android_thread_id_t androidGetThreadId()
{
    return (android_thread_id_t)GetCurrentThreadId();
}

// ----------------------------------------------------------------------------
#else
#error "Threads not supported"
#endif

// ----------------------------------------------------------------------------

#if 0
#pragma mark -
#pragma mark Common Thread functions
#endif

int androidCreateThread(android_thread_func_t fn, void* arg)
{
    return createThreadEtc(fn, arg);
}

int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
{
    return createThreadEtc(fn, arg, "android:unnamed_thread",
                           PRIORITY_DEFAULT, 0, id);
}

static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;

int androidCreateThreadEtc(android_thread_func_t entryFunction,
                            void *userData,
                            const char* threadName,
                            int32_t threadPriority,
                            size_t threadStackSize,
                            android_thread_id_t *threadId)
{
    return gCreateThreadFn(entryFunction, userData, threadName,
        threadPriority, threadStackSize, threadId);
}

void androidSetCreateThreadFunc(android_create_thread_fn func)
{
    gCreateThreadFn = func;
}

namespace android {

/*
 * ===========================================================================
 *      Mutex class
 * ===========================================================================
 */

#if 0
#pragma mark -
#pragma mark Mutex
#endif

#if defined(HAVE_PTHREADS) && !defined(HAVE_FUTEX)
/*
 * Simple pthread wrapper.
 */

Mutex::Mutex()
{
    _init();
}

Mutex::Mutex(const char* name)
{
    // XXX: name not used for now
    _init();
}

void Mutex::_init()
{
    pthread_mutex_t* pMutex = new pthread_mutex_t;
    pthread_mutex_init(pMutex, NULL);
    mState = pMutex;
}

Mutex::~Mutex()
{
    delete (pthread_mutex_t*) mState;
}

status_t Mutex::lock()
{
    int res;
    while ((res=pthread_mutex_lock((pthread_mutex_t*) mState)) == EINTR) ;
    return -res;
}

void Mutex::unlock()
{
    pthread_mutex_unlock((pthread_mutex_t*) mState);
}

status_t Mutex::tryLock()
{
    int res;
    while ((res=pthread_mutex_trylock((pthread_mutex_t*) mState)) == EINTR) ;
    return -res;
}

#elif defined(HAVE_FUTEX)
#if 0
#pragma mark -
#endif

#define STATE ((futex_mutex_t*) (&mState))

Mutex::Mutex()
{
    _init();
}

Mutex::Mutex(const char* name)
{
    _init();
}

void
Mutex::_init()
{
    futex_mutex_init(STATE);
}

Mutex::~Mutex()
{
}

status_t Mutex::lock()
{
    int res;
    while ((res=futex_mutex_lock(STATE, FUTEX_WAIT_INFINITE)) == EINTR) ;
    return -res;
}

void Mutex::unlock()
{
    futex_mutex_unlock(STATE);
}

status_t Mutex::tryLock()
{
    int res;
    while ((res=futex_mutex_trylock(STATE)) == EINTR) ;
    return -res;
}
#undef STATE

#elif defined(HAVE_WIN32_THREADS)
#if 0
#pragma mark -
#endif

Mutex::Mutex()
{
    HANDLE hMutex;

    assert(sizeof(hMutex) == sizeof(mState));

    hMutex = CreateMutex(NULL, FALSE, NULL);
    mState = (void*) hMutex;
}

Mutex::Mutex(const char* name)
{
    // XXX: name not used for now
    HANDLE hMutex;

    hMutex = CreateMutex(NULL, FALSE, NULL);
    mState = (void*) hMutex;
}

Mutex::~Mutex()
{
    CloseHandle((HANDLE) mState);
}

status_t Mutex::lock()
{
    DWORD dwWaitResult;
    dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
    return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
}

void Mutex::unlock()
{
    if (!ReleaseMutex((HANDLE) mState))
        LOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
}

status_t Mutex::tryLock()
{
    DWORD dwWaitResult;

    dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
    if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
        LOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
    return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
}

#else
#error "Somebody forgot to implement threads for this platform."
#endif


/*
 * ===========================================================================
 *      Condition class
 * ===========================================================================
 */

#if 0
#pragma mark -
#pragma mark Condition
#endif

#if defined(HAVE_PTHREADS) && !defined(HAVE_FUTEX)

/*
 * Constructor.  This is a simple pthread wrapper.
 */
Condition::Condition()
{
    pthread_cond_t* pCond = new pthread_cond_t;

    pthread_cond_init(pCond, NULL);
    mState = pCond;
}

/*
 * Destructor.
 */
Condition::~Condition()
{
    pthread_cond_destroy((pthread_cond_t*) mState);
    delete (pthread_cond_t*) mState;
}

/*
 * Wait on a condition variable.  Lock the mutex before calling.
 */

status_t Condition::wait(Mutex& mutex)
{
    assert(mutex.mState != NULL);

    int cc;
    while ((cc = pthread_cond_wait((pthread_cond_t*)mState,
                (pthread_mutex_t*) mutex.mState)) == EINTR) ;
    return -cc;
}

status_t Condition::wait(Mutex& mutex, nsecs_t abstime)
{
    assert(mutex.mState != NULL);

    struct timespec ts;
    ts.tv_sec = abstime/1000000000;
    ts.tv_nsec = abstime-(ts.tv_sec*1000000000);
    
    int cc;
    while ((cc = pthread_cond_timedwait((pthread_cond_t*)mState,
            (pthread_mutex_t*) mutex.mState, &ts)) == EINTR) ;
    return -cc;
}

status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
{
    return wait(mutex, systemTime()+reltime);
}

/*
 * Signal the condition variable, allowing one thread to continue.
 */
void Condition::signal()
{
    pthread_cond_signal((pthread_cond_t*) mState);
}

/*
 * Signal the condition variable, allowing all threads to continue.
 */
void Condition::broadcast()
{
    pthread_cond_broadcast((pthread_cond_t*) mState);
}

#elif defined(HAVE_FUTEX)
#if 0
#pragma mark -
#endif

#define STATE ((futex_cond_t*) (&mState))

/*
 * Constructor.  This is a simple pthread wrapper.
 */
Condition::Condition()
{
    futex_cond_init(STATE);
}

/*
 * Destructor.
 */
Condition::~Condition()
{
}

/*
 * Wait on a condition variable.  Lock the mutex before calling.
 */

status_t Condition::wait(Mutex& mutex)
{
    assert(mutex.mState != NULL);

    int res;
    while ((res = futex_cond_wait(STATE,
        (futex_mutex_t*)(&mutex.mState), FUTEX_WAIT_INFINITE)) == -EINTR) ;

    return -res;
}

status_t Condition::wait(Mutex& mutex, nsecs_t abstime)
{
    nsecs_t reltime = abstime - systemTime();
    if (reltime <= 0) return true;
    return waitRelative(mutex, reltime);
}

status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
{
    assert(mutex.mState != NULL);
    int res;
    unsigned msec = ns2ms(reltime);
    if(msec == 0)
        return true;
    // This code will not time out at the correct time if interrupted by signals
    while ((res = futex_cond_wait(STATE,
        (futex_mutex_t*)(&mutex.mState), msec)) == -EINTR) ;
    return res;
}

/*
 * Signal the condition variable, allowing one thread to continue.
 */
void Condition::signal()
{
    futex_cond_signal(STATE);
}

/*
 * Signal the condition variable, allowing all threads to continue.
 */
void Condition::broadcast()
{
    futex_cond_broadcast(STATE);
}

#undef STATE

#elif defined(HAVE_WIN32_THREADS)
#if 0
#pragma mark -
#endif

/*
 * Windows doesn't have a condition variable solution.  It's possible
 * to create one, but it's easy to get it wrong.  For a discussion, and
 * the origin of this implementation, see:
 *
 *  http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
 *
 * The implementation shown on the page does NOT follow POSIX semantics.
 * As an optimization they require acquiring the external mutex before
 * calling signal() and broadcast(), whereas POSIX only requires grabbing
 * it before calling wait().  The implementation here has been un-optimized
 * to have the correct behavior.
 */
typedef struct WinCondition {
    // Number of waiting threads.
    int                 waitersCount;

    // Serialize access to waitersCount.
    CRITICAL_SECTION    waitersCountLock;

    // Semaphore used to queue up threads waiting for the condition to
    // become signaled.
    HANDLE              sema;

    // An auto-reset event used by the broadcast/signal thread to wait
    // for all the waiting thread(s) to wake up and be released from
    // the semaphore.
    HANDLE              waitersDone;

    // This mutex wouldn't be necessary if we required that the caller
    // lock the external mutex before calling signal() and broadcast().
    // I'm trying to mimic pthread semantics though.
    HANDLE              internalMutex;

    // Keeps track of whether we were broadcasting or signaling.  This
    // allows us to optimize the code if we're just signaling.
    bool                wasBroadcast;

    status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
    {
        // Increment the wait count, avoiding race conditions.
        EnterCriticalSection(&condState->waitersCountLock);
        condState->waitersCount++;
        //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
        //    condState->waitersCount, getThreadId());
        LeaveCriticalSection(&condState->waitersCountLock);
    
        DWORD timeout = INFINITE;
        if (abstime) {
            nsecs_t reltime = *abstime - systemTime();
            if (reltime < 0)
                reltime = 0;
            timeout = reltime/1000000;
        }
        
        // Atomically release the external mutex and wait on the semaphore.
        DWORD res =
            SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);
    
        //printf("+++ wait: awake (tid=%ld)\n", getThreadId());
    
        // Reacquire lock to avoid race conditions.
        EnterCriticalSection(&condState->waitersCountLock);
    
        // No longer waiting.
        condState->waitersCount--;
    
        // Check to see if we're the last waiter after a broadcast.
        bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);
    
        //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
        //    lastWaiter, condState->wasBroadcast, condState->waitersCount);
    
        LeaveCriticalSection(&condState->waitersCountLock);
    
        // If we're the last waiter thread during this particular broadcast
        // then signal broadcast() that we're all awake.  It'll drop the
        // internal mutex.
        if (lastWaiter) {
            // Atomically signal the "waitersDone" event and wait until we
            // can acquire the internal mutex.  We want to do this in one step
            // because it ensures that everybody is in the mutex FIFO before
            // any thread has a chance to run.  Without it, another thread
            // could wake up, do work, and hop back in ahead of us.
            SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
                INFINITE, FALSE);
        } else {
            // Grab the internal mutex.
            WaitForSingleObject(condState->internalMutex, INFINITE);
        }
    
        // Release the internal and grab the external.
        ReleaseMutex(condState->internalMutex);
        WaitForSingleObject(hMutex, INFINITE);
    
        return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
    }
} WinCondition;

/*
 * Constructor.  Set up the WinCondition stuff.
 */
Condition::Condition()
{
    WinCondition* condState = new WinCondition;

    condState->waitersCount = 0;
    condState->wasBroadcast = false;
    // semaphore: no security, initial value of 0
    condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
    InitializeCriticalSection(&condState->waitersCountLock);
    // auto-reset event, not signaled initially
    condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
    // used so we don't have to lock external mutex on signal/broadcast
    condState->internalMutex = CreateMutex(NULL, FALSE, NULL);

    mState = condState;
}

/*
 * Destructor.  Free Windows resources as well as our allocated storage.
 */
Condition::~Condition()
{
    WinCondition* condState = (WinCondition*) mState;
    if (condState != NULL) {
        CloseHandle(condState->sema);
        CloseHandle(condState->waitersDone);
        delete condState;
    }
}


status_t Condition::wait(Mutex& mutex)
{
    WinCondition* condState = (WinCondition*) mState;
    HANDLE hMutex = (HANDLE) mutex.mState;
    
    return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
}

status_t Condition::wait(Mutex& mutex, nsecs_t abstime)
{
    WinCondition* condState = (WinCondition*) mState;
    HANDLE hMutex = (HANDLE) mutex.mState;

    return ((WinCondition*)mState)->wait(condState, hMutex, &abstime);
}

status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
{
    return wait(mutex, systemTime()+reltime);
}

/*
 * Signal the condition variable, allowing one thread to continue.
 */
void Condition::signal()
{
    WinCondition* condState = (WinCondition*) mState;

    // Lock the internal mutex.  This ensures that we don't clash with
    // broadcast().
    WaitForSingleObject(condState->internalMutex, INFINITE);

    EnterCriticalSection(&condState->waitersCountLock);
    bool haveWaiters = (condState->waitersCount > 0);
    LeaveCriticalSection(&condState->waitersCountLock);

    // If no waiters, then this is a no-op.  Otherwise, knock the semaphore
    // down a notch.
    if (haveWaiters)
        ReleaseSemaphore(condState->sema, 1, 0);

    // Release internal mutex.
    ReleaseMutex(condState->internalMutex);
}

/*
 * Signal the condition variable, allowing all threads to continue.
 *
 * First we have to wake up all threads waiting on the semaphore, then
 * we wait until all of the threads have actually been woken before
 * releasing the internal mutex.  This ensures that all threads are woken.
 */
void Condition::broadcast()
{
    WinCondition* condState = (WinCondition*) mState;

    // Lock the internal mutex.  This keeps the guys we're waking up
    // from getting too far.
    WaitForSingleObject(condState->internalMutex, INFINITE);

    EnterCriticalSection(&condState->waitersCountLock);
    bool haveWaiters = false;

    if (condState->waitersCount > 0) {
        haveWaiters = true;
        condState->wasBroadcast = true;
    }

    if (haveWaiters) {
        // Wake up all the waiters.
        ReleaseSemaphore(condState->sema, condState->waitersCount, 0);

        LeaveCriticalSection(&condState->waitersCountLock);

        // Wait for all awakened threads to acquire the counting semaphore.
        // The last guy who was waiting sets this.
        WaitForSingleObject(condState->waitersDone, INFINITE);

        // Reset wasBroadcast.  (No crit section needed because nobody
        // else can wake up to poke at it.)
        condState->wasBroadcast = 0;
    } else {
        // nothing to do
        LeaveCriticalSection(&condState->waitersCountLock);
    }

    // Release internal mutex.
    ReleaseMutex(condState->internalMutex);
}

#else
#error "condition variables not supported on this platform"
#endif


/*
 * ===========================================================================
 *      ReadWriteLock class
 * ===========================================================================
 */

#if 0
#pragma mark -
#pragma mark ReadWriteLock
#endif

/*
 * Add a reader.  Readers are nice.  They share.
 */
void ReadWriteLock::lockForRead()
{
    mLock.lock();
    while (mNumWriters > 0) {
        LOG(LOG_DEBUG, "thread", "+++ lockForRead: waiting\n");
        mReadWaiter.wait(mLock);
    }
    assert(mNumWriters == 0);
    mNumReaders++;
#if defined(PRINT_RENDER_TIMES)
    if (mNumReaders == 1)
        mDebugTimer.start();
#endif
    mLock.unlock();
}

/*
 * Try to add a reader.  If it doesn't work right away, return "false".
 */
bool ReadWriteLock::tryLockForRead()
{
    mLock.lock();
    if (mNumWriters > 0) {
        mLock.unlock();
        return false;
    }
    assert(mNumWriters == 0);
    mNumReaders++;
#if defined(PRINT_RENDER_TIMES)
    if (mNumReaders == 1)
        mDebugTimer.start();
#endif
    mLock.unlock();
    return true;
}

/*
 * Remove a reader.
 */
void ReadWriteLock::unlockForRead()
{
    mLock.lock();
    if (mNumReaders == 0) {
        LOG(LOG_WARN, "thread",
            "WARNING: unlockForRead requested, but not locked\n");
        return;
    }
    assert(mNumReaders > 0);
    assert(mNumWriters == 0);
    mNumReaders--;
    if (mNumReaders == 0) {           // last reader?
#if defined(PRINT_RENDER_TIMES)
        mDebugTimer.stop();
        printf(" rdlk held %.3f msec\n",
            (double) mDebugTimer.durationUsecs() / 1000.0);
#endif
        //printf("+++ signaling writers (if any)\n");
        mWriteWaiter.signal();      // wake one writer (if any)
    }
    mLock.unlock();
}

/*
 * Add a writer.  This requires exclusive access to the object.
 */
void ReadWriteLock::lockForWrite()
{
    mLock.lock();
    while (mNumReaders > 0 || mNumWriters > 0) {
        LOG(LOG_DEBUG, "thread", "+++ lockForWrite: waiting\n");
        mWriteWaiter.wait(mLock);
    }
    assert(mNumReaders == 0);
    assert(mNumWriters == 0);
    mNumWriters++;
#if defined(PRINT_RENDER_TIMES)
    mDebugTimer.start();
#endif
    mLock.unlock();
}

/*
 * Try to add a writer.  If it doesn't work right away, return "false".
 */
bool ReadWriteLock::tryLockForWrite()
{
    mLock.lock();
    if (mNumReaders > 0 || mNumWriters > 0) {
        mLock.unlock();
        return false;
    }
    assert(mNumReaders == 0);
    assert(mNumWriters == 0);
    mNumWriters++;
#if defined(PRINT_RENDER_TIMES)
    mDebugTimer.start();
#endif
    mLock.unlock();
    return true;
}

/*
 * Remove a writer.
 */
void ReadWriteLock::unlockForWrite()
{
    mLock.lock();
    if (mNumWriters == 0) {
        LOG(LOG_WARN, "thread",
            "WARNING: unlockForWrite requested, but not locked\n");
        return;
    }
    assert(mNumWriters == 1);
    mNumWriters--;
#if defined(PRINT_RENDER_TIMES)
    mDebugTimer.stop();
    //printf(" wrlk held %.3f msec\n",
    //    (double) mDebugTimer.durationUsecs() / 1000.0);
#endif
    // mWriteWaiter.signal();       // should other writers get first dibs?
    //printf("+++ signaling readers (if any)\n");
    mReadWaiter.broadcast();        // wake all readers (if any)
    mLock.unlock();
}

// ----------------------------------------------------------------------------

#if 0
#pragma mark -
#pragma mark Thread::Thread
#endif

/*
 * This is our thread object!
 */

Thread::Thread(bool canCallJava)
    :   mCanCallJava(canCallJava),
        mThread(thread_id_t(-1)),
        mLock("Thread::mLock"),
        mStatus(NO_ERROR),
        mExitPending(false), mRunning(false)
{
}

Thread::~Thread()
{
}

status_t Thread::readyToRun()
{
    return NO_ERROR;
}

status_t Thread::run(const char* name, int32_t priority, size_t stack)
{
    Mutex::Autolock _l(mLock);

    if (mRunning) {
        // thread already started
        return INVALID_OPERATION;
    }

    // reset status and exitPending to their default value, so we can
    // try again after an error happened (either below, or in readyToRun())
    mStatus = NO_ERROR;
    mExitPending = false;
    mThread = thread_id_t(-1);
    
    // hold a strong reference on ourself
    mHoldSelf = this;

    bool res;
    if (mCanCallJava) {
        res = createThreadEtc(_threadLoop,
                this, name, priority, stack, &mThread);
    } else {
        res = androidCreateRawThreadEtc(_threadLoop,
                this, name, priority, stack, &mThread);
    }
    
    if (res == false) {
        mStatus = UNKNOWN_ERROR;   // something happened!
        mRunning = false;
        mThread = thread_id_t(-1);
    }
    
    if (mStatus < 0) {
        // something happened, don't leak
        mHoldSelf.clear();
    }
    
    return mStatus;
}

int Thread::_threadLoop(void* user)
{
    Thread* const self = static_cast<Thread*>(user);
    sp<Thread> strong(self->mHoldSelf);
    wp<Thread> weak(strong);
    self->mHoldSelf.clear();

    // we're about to run...
    self->mStatus = self->readyToRun();
    if (self->mStatus!=NO_ERROR || self->mExitPending) {
        // pretend the thread never started...
        self->mExitPending = false;
        self->mRunning = false;
        return 0;
    }
    
    // thread is running now
    self->mRunning = true;

    do {
        bool result = self->threadLoop();
        if (result == false || self->mExitPending) {
            self->mExitPending = true;
            self->mLock.lock();
            self->mRunning = false;
            self->mThreadExitedCondition.signal();
            self->mLock.unlock();
            break;
        }
        
        // Release our strong reference, to let a chance to the thread
        // to die a peaceful death.
        strong.clear();
        // And immediately, reacquire a strong reference for the next loop
        strong = weak.promote();
    } while(strong != 0);
    
    return 0;
}

void Thread::requestExit()
{
    mExitPending = true;
}

status_t Thread::requestExitAndWait()
{
    if (mStatus == OK) {

        if (mThread == getThreadId()) {
            LOGW(
            "Thread (this=%p): don't call waitForExit() from this "
            "Thread object's thread. It's a guaranteed deadlock!",
            this);
            return WOULD_BLOCK;
        }
        
        requestExit();

        Mutex::Autolock _l(mLock);
        while (mRunning == true) {
            mThreadExitedCondition.wait(mLock);
        }
        mExitPending = false;
    }
    return mStatus;
}

bool Thread::exitPending() const
{
    return mExitPending;
}



};  // namespace android