File: fthreads.c

package info (click to toggle)
hercules 3.13-9
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 14,392 kB
  • sloc: ansic: 175,124; sh: 8,792; makefile: 760; perl: 149
file content (1824 lines) | stat: -rw-r--r-- 60,084 bytes parent folder | download | duplicates (5)
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
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
/*  FTHREADS.C  (c) Copyright "Fish" (David B. Trout), 2001-2009     */
/*              Fish's WIN32 version of pthreads                     */

////////////////////////////////////////////////////////////////////////////////////
// (c) Copyright "Fish" (David B. Trout), 2001-2009. Released under the Q Public License
// (http://www.hercules-390.org/herclic.html) as modifications to Hercules.
////////////////////////////////////////////////////////////////////////////////////

#include "hstdinc.h"

#define _FTHREADS_C_
#define _HUTIL_DLL_

#include "hercules.h"
#include "fthreads.h"

#if defined(OPTION_FTHREADS)

////////////////////////////////////////////////////////////////////////////////////
// Private internal fthreads structures...

typedef struct _tagFT_MUTEX             // fthread "mutex" structure
{
    CRITICAL_SECTION  MutexLock;        // (lock for accessing this data)
    DWORD             dwMutexMagic;     // (magic number)
    HANDLE            hUnlockedEvent;   // (signalled while NOT locked)
    DWORD             dwMutexType;      // (type of mutex (normal, etc))
    DWORD             dwLockOwner;      // (thread-id of who owns it)
    int               nLockedCount;     // (#of times lock acquired)
}
FT_MUTEX, *PFT_MUTEX;

typedef struct _tagFT_COND_VAR          // fthread "condition variable" structure
{
    CRITICAL_SECTION  CondVarLock;      // (lock for accessing this data)
    DWORD             dwCondMagic;      // (magic number)
    HANDLE            hSigXmitEvent;    // set during signal transmission
    HANDLE            hSigRecvdEvent;   // set once signal received by every-
                                        // one that's supposed to receive it.
    BOOL              bBroadcastSig;    // TRUE = "broadcast", FALSE = "signal"
    int               nNumWaiting;      // #of threads waiting to receive signal
}
FT_COND_VAR, *PFT_COND_VAR;

////////////////////////////////////////////////////////////////////////////////////
// So we can tell whether our structures have been properly initialized or not...

#define  FT_MUTEX_MAGIC   0x4D767478    // "Mutx" in ASCII
#define  FT_COND_MAGIC    0x436F6E64    // "Cond" in ASCII
#define  FT_ATTR_MAGIC    0x41747472    // "Attr" in ASCII

////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
// Private internal fthreads functions...

static BOOL  IsValidMutexType ( DWORD dwMutexType )
{
    return (0
//      || FTHREAD_MUTEX_DEFAULT    == dwMutexType  // (FTHREAD_MUTEX_RECURSIVE)
        || FTHREAD_MUTEX_RECURSIVE  == dwMutexType
        || FTHREAD_MUTEX_ERRORCHECK == dwMutexType
//      || FTHREAD_MUTEX_NORMAL     == dwMutexType  // (not currently supported)
    );
}

////////////////////////////////////////////////////////////////////////////////////

static FT_MUTEX*  MallocFT_MUTEX ( )
{
    FT_MUTEX*  pFT_MUTEX = (FT_MUTEX*) malloc ( sizeof ( FT_MUTEX ) );
    if ( !pFT_MUTEX ) return NULL;
    memset ( pFT_MUTEX, 0xCD, sizeof ( FT_MUTEX ) );
    return pFT_MUTEX;
}

////////////////////////////////////////////////////////////////////////////////////

static BOOL  InitializeFT_MUTEX
(
    FT_MUTEX*     pFT_MUTEX,
    DWORD         dwMutexType
)
{
    // Note: UnlockedEvent created initially signalled

    if ( !(pFT_MUTEX->hUnlockedEvent = MyCreateEvent ( NULL, TRUE, TRUE, NULL )) )
    {
        memset ( pFT_MUTEX, 0xCD, sizeof ( FT_MUTEX ) );
        return FALSE;
    }

    MyInitializeCriticalSection ( &pFT_MUTEX->MutexLock );

    pFT_MUTEX->dwMutexMagic   = FT_MUTEX_MAGIC;
    pFT_MUTEX->dwMutexType    = dwMutexType;
    pFT_MUTEX->dwLockOwner    = 0;
    pFT_MUTEX->nLockedCount   = 0;

    return TRUE;
}

////////////////////////////////////////////////////////////////////////////////////

static BOOL  UninitializeFT_MUTEX
(
    FT_MUTEX*    pFT_MUTEX
)
{
    if ( pFT_MUTEX->nLockedCount > 0 )
        return FALSE;   // (still in use)

    ASSERT( IsEventSet ( pFT_MUTEX->hUnlockedEvent ) );

    MyDeleteEvent ( pFT_MUTEX->hUnlockedEvent );
    MyDeleteCriticalSection ( &pFT_MUTEX->MutexLock );

    memset ( pFT_MUTEX, 0xCD, sizeof ( FT_MUTEX ) );

    return TRUE;
}

////////////////////////////////////////////////////////////////////////////////////

static FT_COND_VAR*  MallocFT_COND_VAR ( )
{
    FT_COND_VAR*  pFT_COND_VAR = (FT_COND_VAR*) malloc ( sizeof ( FT_COND_VAR ) );
    if ( !pFT_COND_VAR ) return NULL;
    memset ( pFT_COND_VAR, 0xCD, sizeof ( FT_COND_VAR ) );
    return pFT_COND_VAR;
}

////////////////////////////////////////////////////////////////////////////////////

static BOOL  InitializeFT_COND_VAR
(
    FT_COND_VAR*  pFT_COND_VAR
)
{
    if ( ( pFT_COND_VAR->hSigXmitEvent = MyCreateEvent ( NULL, TRUE, FALSE, NULL ) ) )
    {
        // Note: hSigRecvdEvent created initially signaled

        if ( ( pFT_COND_VAR->hSigRecvdEvent = MyCreateEvent ( NULL, TRUE, TRUE, NULL ) ) )
        {
            MyInitializeCriticalSection ( &pFT_COND_VAR->CondVarLock );

            pFT_COND_VAR->dwCondMagic   = FT_COND_MAGIC;
            pFT_COND_VAR->bBroadcastSig = FALSE;
            pFT_COND_VAR->nNumWaiting   = 0;

            return TRUE;
        }

        MyDeleteEvent ( pFT_COND_VAR->hSigXmitEvent );
    }

    memset ( pFT_COND_VAR, 0xCD, sizeof ( FT_COND_VAR ) );

    return FALSE;
}

////////////////////////////////////////////////////////////////////////////////////

static BOOL  UninitializeFT_COND_VAR
(
    FT_COND_VAR*  pFT_COND_VAR
)
{
    if (0
        ||  pFT_COND_VAR->nNumWaiting
        ||  IsEventSet ( pFT_COND_VAR->hSigXmitEvent  )
        || !IsEventSet ( pFT_COND_VAR->hSigRecvdEvent )
    )
        return FALSE;

    MyDeleteEvent ( pFT_COND_VAR->hSigXmitEvent  );
    MyDeleteEvent ( pFT_COND_VAR->hSigRecvdEvent );

    MyDeleteCriticalSection ( &pFT_COND_VAR->CondVarLock );

    memset ( pFT_COND_VAR, 0xCD, sizeof ( FT_COND_VAR ) );

    return TRUE;
}

////////////////////////////////////////////////////////////////////////////////////

static BOOL  TryEnterFT_MUTEX
(
    FT_MUTEX*    pFT_MUTEX
)
{
    BOOL   bSuccess;
    DWORD  dwThreadId = GetCurrentThreadId();

    if ( hostinfo.trycritsec_avail )
    {
        bSuccess = MyTryEnterCriticalSection ( &pFT_MUTEX->MutexLock );

        if ( bSuccess )
        {
            pFT_MUTEX->nLockedCount++;
            ASSERT( pFT_MUTEX->nLockedCount > 0 );
            pFT_MUTEX->dwLockOwner = dwThreadId;
        }
    }
    else
    {
        MyEnterCriticalSection ( &pFT_MUTEX->MutexLock );

        ASSERT ( pFT_MUTEX->nLockedCount >= 0 );

        bSuccess = ( pFT_MUTEX->nLockedCount <= 0 || pFT_MUTEX->dwLockOwner == dwThreadId );

        if ( bSuccess )
        {
            pFT_MUTEX->nLockedCount++;
            ASSERT ( pFT_MUTEX->nLockedCount > 0 );
            pFT_MUTEX->dwLockOwner = dwThreadId;
            MyResetEvent ( pFT_MUTEX->hUnlockedEvent );
        }

        MyLeaveCriticalSection ( &pFT_MUTEX->MutexLock );
    }

    return bSuccess;
}

////////////////////////////////////////////////////////////////////////////////////

static void  EnterFT_MUTEX
(
    FT_MUTEX*    pFT_MUTEX
)
{
    DWORD  dwThreadId = GetCurrentThreadId();

    if ( hostinfo.trycritsec_avail )
    {
        MyEnterCriticalSection ( &pFT_MUTEX->MutexLock );
        pFT_MUTEX->dwLockOwner = dwThreadId;
        pFT_MUTEX->nLockedCount++;
        ASSERT ( pFT_MUTEX->nLockedCount > 0 );
    }
    else
    {
        for (;;)
        {
            MyEnterCriticalSection ( &pFT_MUTEX->MutexLock );
            ASSERT ( pFT_MUTEX->nLockedCount >= 0 );
            if ( pFT_MUTEX->nLockedCount <= 0 || pFT_MUTEX->dwLockOwner == dwThreadId ) break;
            MyLeaveCriticalSection ( &pFT_MUTEX->MutexLock );
            MyWaitForSingleObject ( pFT_MUTEX->hUnlockedEvent, INFINITE );
        }

        MyResetEvent ( pFT_MUTEX->hUnlockedEvent );
        pFT_MUTEX->dwLockOwner = dwThreadId;
        pFT_MUTEX->nLockedCount++;
        ASSERT ( pFT_MUTEX->nLockedCount > 0 );
        MyLeaveCriticalSection ( &pFT_MUTEX->MutexLock );
    }
}

////////////////////////////////////////////////////////////////////////////////////

static void  LeaveFT_MUTEX
(
    FT_MUTEX*    pFT_MUTEX
)
{
    if ( hostinfo.trycritsec_avail )
    {
        ASSERT ( pFT_MUTEX->nLockedCount > 0 );
        pFT_MUTEX->nLockedCount--;
        if ( pFT_MUTEX->nLockedCount <= 0 )
            pFT_MUTEX->dwLockOwner = 0;
        MyLeaveCriticalSection ( &pFT_MUTEX->MutexLock );
    }
    else
    {
        MyEnterCriticalSection ( &pFT_MUTEX->MutexLock );
        ASSERT ( pFT_MUTEX->nLockedCount > 0 );
        pFT_MUTEX->nLockedCount--;
        if ( pFT_MUTEX->nLockedCount <= 0 )
        {
            pFT_MUTEX->dwLockOwner = 0;
            MySetEvent ( pFT_MUTEX->hUnlockedEvent );
        }
        MyLeaveCriticalSection ( &pFT_MUTEX->MutexLock );
    }
}

////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
// Now we get to the "meat" of fthreads...
//
// The below function atomically releases the caller's mutex and registers the fact
// that the caller wishes to wait on their condition variable (or rather the other
// way around: it first registers the fact that the caller wishes to wait on the
// condition by first acquiring the condition variable lock and then registering
// the wait and THEN afterwards (once the wait has been registered and condition
// variable lock acquired) releases the original mutex). This ensures that no one
// can "sneak a signal past us" from the time this function is called until we can
// manage to register the wait request since no signals can ever be sent while the
// condition variable is locked.

static int  BeginWait
(
    FT_COND_VAR*      pFT_COND_VAR,
    fthread_mutex_t*  pFTUSER_MUTEX
)
{
    int        rc;
    FT_MUTEX*  pFT_MUTEX;

    if (0
        || !pFT_COND_VAR                                          // (invalid ptr)
        ||  pFT_COND_VAR -> dwCondMagic  != FT_COND_MAGIC         // (not initialized)
        || !pFTUSER_MUTEX                                         // (invalid ptr)
        ||  pFTUSER_MUTEX-> dwMutexMagic != FT_MUTEX_MAGIC        // (not initialized)
        || !(pFT_MUTEX = pFTUSER_MUTEX->hMutex)                   // (invalid ptr)
//      || !pFT_MUTEX                                             // (invalid ptr)
        ||  pFT_MUTEX    -> dwMutexMagic != FT_MUTEX_MAGIC        // (not initialized)
    )
        return RC(EINVAL);

    if (0
        ||  pFT_MUTEX    -> dwLockOwner  != GetCurrentThreadId()  // (mutex not owned)
        ||  pFT_MUTEX    -> nLockedCount <= 0                     // (mutex not locked)
    )
        return RC(EPERM);

    // First, acquire the fthreads condition variable lock...

    for (;;)
    {
        MyEnterCriticalSection ( &pFT_COND_VAR->CondVarLock );

        // It is always safe to proceed if the prior signal was completely
        // processed (received by everyone who was supposed to receive it)

        if ( IsEventSet ( pFT_COND_VAR->hSigRecvdEvent ) )
            break;

        // Prior signal not completely received yet... Verify that it is
        // still being transmitted...

        ASSERT ( IsEventSet ( pFT_COND_VAR->hSigXmitEvent ) );

        // If no one is currently waiting to receive [this signal not yet
        // completely received and still being transmitted], then we can
        // go ahead and receive it right now *regardless* of what type of
        // signal it is ("signal" or "broadcast") since we're *obviously*
        // the one who is supposed to receive it (since we ARE trying to
        // wait on it after all and it IS being transmitted. The 'xmit'
        // event is *always* turned off once everyone [who is *supposed*
        // to receive the signal] *has* received the signal. Thus, since
        // it's still being transmitted, that means *not* everyone who
        // *should* receive it *has* received it yet, and thus we can be
        // absolutely certain that we indeed *should* therefore receive it
        // since we *are* after all waiting for it).

        // Otherwise (prior signal not completely processed AND there are
        // still others waiting to receive it too (as well as us)), then if
        // it's a "broadcast" type signal, we can go ahead and receive that
        // type of signal too as well (along with the others); we just came
        // to the party a little bit late (but nevertheless in the nick of
        // time!), that's all...

        if ( !pFT_COND_VAR->nNumWaiting || pFT_COND_VAR->bBroadcastSig )
            break;

        // Otherwise it's a "signal" type signal (and not a broadcast type)
        // that hasn't been completely received yet, meaning only ONE thread
        // should be released. Thus, since there's already a thread (or more
        // than one thread) already waiting/trying to receive it, we need to
        // let [one of] THEM receive it and NOT US. Thus we go back to sleep
        // and wait for the signal processing currently in progress to finish
        // releasing the proper number of threads first. Only once that has
        // happened can we then be allowed to try and catch whatever signal
        // happens to come along next...

        MyLeaveCriticalSection ( &pFT_COND_VAR->CondVarLock );

        // (Programming Note: technically we should really be checking our
        // return code from the below wait call too)

        MyWaitForSingleObject ( pFT_COND_VAR->hSigRecvdEvent, INFINITE );
    }

    // Register the caller's wait request while we still have control
    // over this condition variable...

    pFT_COND_VAR->nNumWaiting++;        // (register wait request)

    // Now release the original mutex and thus any potential signalers...
    // (but note that no signal can actually ever be sent per se until
    // the condition variable which we currently have locked is first
    // released, which gets done in the WaitForTransmission function).

    if
    (
        (
            rc = fthread_mutex_unlock
            (
                pFTUSER_MUTEX
            )
        )
        != 0
    )
    {
        // Oops! Something went wrong. We couldn't release the original
        // caller's original mutex. Since we've already registered their
        // wait and already have the condition variable locked, we need
        // to first de-register their wait and release the condition var-
        // iable lock before returning our error (i.e. we essentially
        // need to back out what we previously did just above).

        logmsg("fthreads: BeginWait: fthread_mutex_unlock failed! rc=%d\n"
            ,rc );

        pFT_COND_VAR->nNumWaiting--;    // (de-register wait request)

        MyLeaveCriticalSection ( &pFT_COND_VAR->CondVarLock );

        return RC(rc);
    }

    // Our "begin-to-wait-on-condition-variable" task has been successfully
    // completed. We have essentially atomically released the originally mutex
    // and "begun our wait" on it (by registering the fact that there's someone
    // wanting to wait on it). Return to OUR caller with the condition variable
    // still locked (so no signals can be sent nor any threads released until
    // our caller calls the below WaitForTransmission function)...

    return RC(0);   // (success)
}

////////////////////////////////////////////////////////////////////////////////////
// Wait for the condition variable in question to receive a transmission...

static int  WaitForTransmission
(
    FT_COND_VAR*      pFT_COND_VAR,
    struct timespec*  pTimeTimeout     // (NULL == INFINITE wait)
)
{
    DWORD  dwWaitRetCode, dwWaitMilliSecs;

    // If the signal has already arrived (i.e. is still being transmitted)
    // then there's no need to wait for it. Simply return success with the
    // condition variable still locked...

    if ( IsEventSet ( pFT_COND_VAR->hSigXmitEvent ) )
    {
        // There's no need to wait for the signal (transmission)
        // to arrive because it's already been sent! Just return.

        return 0;           // (transmission received!)
    }

    // Our loop to wait for our transmission to arrive...

    do
    {
        // Release condition var lock (so signal (transmission) can
        // be sent) and then wait for the signal (transmission)...

        MyLeaveCriticalSection ( &pFT_COND_VAR->CondVarLock );

        // Need to calculate a timeout value if this is a
        // timed condition wait as opposed to a normal wait...

        // Note that we unfortunately need to do this on each iteration
        // because Window's wait API requires a relative timeout value
        // rather than an absolute TOD timeout value like pthreads...

        if ( !pTimeTimeout )
        {
            dwWaitMilliSecs = INFINITE;
        }
        else
        {
            struct timeval  TimeNow;

            gettimeofday ( &TimeNow, NULL );

            if (TimeNow.tv_sec >  pTimeTimeout->tv_sec
                ||
                (
                    TimeNow.tv_sec == pTimeTimeout->tv_sec
                    &&
                    (TimeNow.tv_usec * 1000) > pTimeTimeout->tv_nsec
                )
            )
            {
                dwWaitMilliSecs = 0;
            }
            else
            {
                dwWaitMilliSecs =
                    ((pTimeTimeout->tv_sec - TimeNow.tv_sec) * 1000) +
                    ((pTimeTimeout->tv_nsec - (TimeNow.tv_usec * 1000)) / 1000000);
            }
        }

        // Finally we get to do the actual wait...

        dwWaitRetCode =
            MyWaitForSingleObject ( pFT_COND_VAR->hSigXmitEvent, dwWaitMilliSecs );

        // A signal (transmission) has been sent; reacquire our condition var lock
        // and receive the transmission (if it's still being transmitted that is)...

        MyEnterCriticalSection ( &pFT_COND_VAR->CondVarLock );

        // The "WAIT_OBJECT_0 == dwWaitRetCode && ..." clause in the below 'while'
        // statement ensures that we will always break out of our wait loop whenever
        // either a timeout occurs or our actual MyWaitForSingleObject call fails
        // for any reason. As long as dwWaitRetCode is WAIT_OBJECT_0 though *AND*
        // our event has still not been signaled yet, then we'll continue looping
        // to wait for a signal (transmission) that we're supposed to receive...

        // Also note that one might at first think/ask: "Gee, Fish, why do we need
        // to check to see if the condition variable's "hSigXmitEvent" event has
        // been set each time (via the 'IsEventSet' macro)? Shouldn't it *always*
        // be set if the above MyWaitForSingleObject call returns??" The answer is
        // of course no, it might NOT [still] be signaled. This is because whenever
        // someone *does* happen to signal it, we will of course be released from
        // our wait (the above MyWaitForSingleObject call) BUT... someone else who
        // was also waiting for it may have managed to grab our condition variable
        // lock before we could and they could have reset it. Thus we need to check
        // it again each time.
    }
    while ( WAIT_OBJECT_0 == dwWaitRetCode && !IsEventSet( pFT_COND_VAR->hSigXmitEvent ) );

    // Our signal (transmission) has either [finally] arrived or else we got
    // tired of waiting for it (i.e. we timed out) or else there was an error...

    if ( WAIT_OBJECT_0 == dwWaitRetCode ) return RC(0);
    if ( WAIT_TIMEOUT  == dwWaitRetCode ) return RC(ETIMEDOUT);

    // Our wait failed! Something is VERY wrong! Maybe the condition variable
    // was prematurely destroyed by someone? <shrug> In any case there's not
    // much we can do about it other than log the fact that it occurred and
    // return the error back to the caller. Their wait request has, believe
    // it or not, actually been completed (although not as they expected it
    // would in all likelihood!)...

    logmsg ( "fthreads: WaitForTransmission: MyWaitForSingleObject failed! dwWaitRetCode=%d (0x%8.8X)\n"
        ,dwWaitRetCode ,dwWaitRetCode );

    return RC(EFAULT);
}

////////////////////////////////////////////////////////////////////////////////////
// Send a "signal" or "broadcast" to a condition variable...

static int  QueueTransmission
(
    FT_COND_VAR*  pFT_COND_VAR,
    BOOL          bXmitType
)
{
    if (0
        || !pFT_COND_VAR                                // (invalid ptr)
        ||  pFT_COND_VAR->dwCondMagic != FT_COND_MAGIC  // (not initialized)
    )
    {
        return RC(EINVAL);    // (invalid parameters were passed)
    }

    // Wait for the condition variable to become free so we can begin transmitting
    // our signal... If the condition variable is still "busy" (in use), then that
    // means threads are still in the process of being released as a result of some
    // prior signal (transmission). Thus we must wait until that work is completed
    // first before we can send our new signal (transmission)...

    for (;;)
    {
        MyEnterCriticalSection ( &pFT_COND_VAR->CondVarLock );
        if ( IsEventSet ( pFT_COND_VAR->hSigRecvdEvent ) ) break;
        MyLeaveCriticalSection ( &pFT_COND_VAR->CondVarLock );
        MyWaitForSingleObject ( pFT_COND_VAR->hSigRecvdEvent, INFINITE );
    }

    // Turn on our transmitter...  (i.e. start transmitting our "signal" to
    // all threads who might be waiting to receive it (if there are any)...

    // If no one has registered their interest in receiving any transmissions
    // associated with this particular condition variable, then they are unfor-
    // tunately a little too late in doing so because we're ready to start our
    // transmission right now! If there's no one to receive our transmission,
    // then it simply gets lost (i.e. a "missed signal" situation has essenti-
    // ally occurred), but then that's not our concern here; our only concern
    // here is to transmit the signal (transmission) and nothing more. Tough
    // beans if there's no one listening to receive it... <shrug>

    if ( pFT_COND_VAR->nNumWaiting )                    // (anyone interested?)
    {
        pFT_COND_VAR->bBroadcastSig = bXmitType;        // (yep! set xmit type)
        MySetEvent   ( pFT_COND_VAR->hSigXmitEvent  );  // (turn on transmitter)
        MyResetEvent ( pFT_COND_VAR->hSigRecvdEvent );  // (serialize reception)
    }

    MyLeaveCriticalSection ( &pFT_COND_VAR->CondVarLock );

    return RC(0);
}

////////////////////////////////////////////////////////////////////////////////////
// A thread has been released as a result of someone's signal or broadcast...

static void  ReceiveXmission
(
    FT_COND_VAR*  pFT_COND_VAR
)
{
    // If we were the only ones supposed to receive the transmission, (or
    // if no one remains to receive any transmissions), then turn off the
    // transmitter (i.e. stop sending the signal) and indicate that it has
    // been completely received all interested parties (i.e. by everyone
    // who was supposed to receive it)...

    pFT_COND_VAR->nNumWaiting--;    // (de-register wait since transmission
                                    //  has been successfully received now)

    // Determine whether any more waiters (threads) should also receive
    // this transmission (i.e. also be released) or whether we should
    // reset (turn off) our transmitter so as to not release any other
    // thread(s) besides ourselves...

    if (0
        || !pFT_COND_VAR->bBroadcastSig         // ("signal" == only us)
        ||  pFT_COND_VAR->nNumWaiting <= 0      // (no one else == only us)
    )
    {
        MyResetEvent ( pFT_COND_VAR->hSigXmitEvent  );   // (turn off transmitter)
        MySetEvent   ( pFT_COND_VAR->hSigRecvdEvent );   // (transmission complete)
    }
}

////////////////////////////////////////////////////////////////////////////////////
// The following function is called just before returning back to the caller. It
// first releases the condition variable lock (since we're now done with it) and
// then reacquires the caller's original mutex before returning [back to the caller].

// We MUST do things in that order! 1) release our condition variable lock, and THEN
// 2) try to reacquire the caller's original mutex. Otherwise a deadlock could occur!

// If we still had the condition variable locked before trying to acquire the caller's
// original mutex, we could easily become blocked if some other thread still already
// owned (had locked) the caller's mutex. We would then be unable to ever release our
// condition variable lock until whoever had the mutex locked first released it, but
// they would never be able to release it because we still had the condition variable
// still locked! Recall that upon entry to a wait call (see previous BeginWait function)
// we acquire the condition variable lock *first* (in order to register the caller's
// wait) before releasing their mutex. Thus, we MUST therefore release our condition
// variable lock FIRST and THEN try reacquiring their original mutex before returning.

static int  ReturnFromWait
(
    FT_COND_VAR*      pFT_COND_VAR,
    fthread_mutex_t*  pFTUSER_MUTEX,
    int               nRetCode
)
{
    int        rc;
    FT_MUTEX*  pFT_MUTEX;

    if (0
        || !pFT_COND_VAR                                          // (invalid ptr)
        ||  pFT_COND_VAR -> dwCondMagic  != FT_COND_MAGIC         // (not initialized)
        || !pFTUSER_MUTEX                                         // (invalid ptr)
        ||  pFTUSER_MUTEX-> dwMutexMagic != FT_MUTEX_MAGIC        // (not initialized)
        || !(pFT_MUTEX = pFTUSER_MUTEX->hMutex)                   // (invalid ptr)
//      || !pFT_MUTEX                                             // (invalid ptr)
        ||  pFT_MUTEX    -> dwMutexMagic != FT_MUTEX_MAGIC        // (not initialized)
    )
        return RC(EINVAL);

    // (let other threads access this condition variable now...)

    MyLeaveCriticalSection ( &pFT_COND_VAR->CondVarLock );

    // (reacquire original mutex before returning back to the original caller...)

    if
    (
        (
            rc = fthread_mutex_lock
            (
                pFTUSER_MUTEX
            )
        )
        != 0
    )
    {
        // Oops! We were unable to reacquire the caller's original mutex! This
        // is actually a catastrophic type of error! The caller expects their
        // mutex to still be owned (locked) by themselves upon return, but we
        // were unable to reacquire it for them! Unfortunately there's nothing
        // we can do about this; the system is essentially hosed at this point.
        // Just log the fact that something went wrong and return. <shrug>

        logmsg("fthreads: ReturnFromWait: fthread_mutex_lock failed! rc=%d\n"
            ,rc );

        return RC(rc);        // (what went wrong)
    }

    // Return to caller with the requested return code. (The caller passes to us
    // the return code they wish to pass back to the original caller, so we just
    // return that same return code back to OUR caller (so they can then pass it
    // back to the original fthreads caller)).

    return RC(nRetCode);      // (as requested)
}

////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
// Threading functions...

LIST_ENTRY        ThreadListHead;   // head list entry of list of joinable threads
CRITICAL_SECTION  ThreadListLock;   // lock for accessing list of joinable threads

#define LockThreadsList()    EnterCriticalSection ( &ThreadListLock )
#define UnlockThreadsList()  LeaveCriticalSection ( &ThreadListLock )

////////////////////////////////////////////////////////////////////////////////////
// internal joinable thread information

typedef struct _tagFTHREAD
{
    LIST_ENTRY  ThreadListLink;     // (links entries together in a chain)
    DWORD       dwThreadID;         // (thread-id)
    HANDLE      hThreadHandle;      // (Win32 thread handle)
    BOOL        bJoinable;          // (whether thread is joinable or detached)
    int         nJoinedCount;       // (#of threads that did join on this one)
    void*       ExitVal;            // (saved thread exit value)
    jmp_buf     JumpBuf;            // (jump buffer for fthread_exit)
}
FTHREAD, *PFTHREAD;

////////////////////////////////////////////////////////////////////////////////////
// (Note: returns with thread list lock still held if found; not held if not found)

static FTHREAD*  FindFTHREAD ( DWORD dwThreadID )
{
    FTHREAD*     pFTHREAD;
    LIST_ENTRY*  pListEntry;

    LockThreadsList();      // (acquire thread list lock)

    pListEntry = ThreadListHead.Flink;

    while ( pListEntry != &ThreadListHead )
    {
        pFTHREAD = CONTAINING_RECORD ( pListEntry, FTHREAD, ThreadListLink );

        pListEntry = pListEntry->Flink;

        if ( pFTHREAD->dwThreadID != dwThreadID )
            continue;

        return pFTHREAD;    // (return with thread list lock still held)
    }

    UnlockThreadsList();    // (release thread list lock)

    return NULL;            // (not found)
}

////////////////////////////////////////////////////////////////////////////////////

typedef struct _ftCallThreadParms
{
    PFT_THREAD_FUNC  pfnTheirThreadFunc;
    void*            pvTheirThreadArgs;
    char*            pszTheirThreadName;
    FTHREAD*         pFTHREAD;
}
FT_CALL_THREAD_PARMS;

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

static DWORD  __stdcall  FTWin32ThreadFunc
(
    void*  pMyArgs
)
{
    FT_CALL_THREAD_PARMS*  pCallTheirThreadParms;
    PFT_THREAD_FUNC        pfnTheirThreadFunc;
    void*                  pvTheirThreadArgs;
    FTHREAD*               pFTHREAD;

    pCallTheirThreadParms = (FT_CALL_THREAD_PARMS*) pMyArgs;

    pfnTheirThreadFunc = pCallTheirThreadParms->pfnTheirThreadFunc;
    pvTheirThreadArgs  = pCallTheirThreadParms->pvTheirThreadArgs;
    pFTHREAD           = pCallTheirThreadParms->pFTHREAD;

    // PROGRAMMING NOTE: -1 == "current calling thread"
    SET_THREAD_NAME_ID ( -1, pCallTheirThreadParms->pszTheirThreadName );

    free ( pCallTheirThreadParms );

    if ( setjmp ( pFTHREAD->JumpBuf ) == 0 )
        pFTHREAD->ExitVal = pfnTheirThreadFunc ( pvTheirThreadArgs );

    LockThreadsList();

    if ( !pFTHREAD->bJoinable )
    {
        // If we are not a joinable thread, we must free our
        // own resources ourselves, but ONLY IF the 'joined'
        // count is zero. If the 'joined' count is NOT zero,
        // then, however it occurred, there is still someone
        // waiting in the join function for us to exit, and
        // thus, we cannot free our resources at this time
        // (since the thread that did the join and which is
        // waiting for us to exit still needs access to our
        // resources). In such a situation the actual freeing
        // of resources is deferred and will be done by the
        // join function itself whenever it's done with them.

        if ( pFTHREAD->nJoinedCount <= 0 )
        {
            CloseHandle ( pFTHREAD->hThreadHandle );
            RemoveListEntry ( &pFTHREAD->ThreadListLink );
            free ( pFTHREAD );
        }
    }

    UnlockThreadsList();

    MyExitThread ( 0 );

    return 0;   // (make compiler happy)
}

////////////////////////////////////////////////////////////////////////////////////
// Create a new thread...

DLL_EXPORT
int  fthread_create
(
    fthread_t*       pdwThreadID,
    fthread_attr_t*  pThreadAttr,
    PFT_THREAD_FUNC  pfnThreadFunc,
    void*            pvThreadArgs,
    char*            pszThreadName
)
{
    static BOOL            bDidInit = FALSE;
    FT_CALL_THREAD_PARMS*  pCallTheirThreadParms;
    size_t                 nStackSize;
    int                    nDetachState;
    FTHREAD*               pFTHREAD;
    HANDLE                 hThread;
    DWORD                  dwThreadID;

    if ( !bDidInit )
    {
        bDidInit = TRUE;
        InitializeListHead ( &ThreadListHead );
        InitializeCriticalSection ( &ThreadListLock );
    }

    if (0
        || !pdwThreadID
        || !pfnThreadFunc
    )
        return RC(EINVAL);

    if ( pThreadAttr )
    {
        if (  pThreadAttr->dwAttrMagic  != FT_ATTR_MAGIC ||
            ( pThreadAttr->nDetachState != FTHREAD_CREATE_DETACHED &&
              pThreadAttr->nDetachState != FTHREAD_CREATE_JOINABLE ) )
            return RC(EINVAL);

        nStackSize   = pThreadAttr->nStackSize;
        nDetachState = pThreadAttr->nDetachState;
    }
    else
    {
        nStackSize   = 0;
        nDetachState = FTHREAD_CREATE_DEFAULT;
    }

    pCallTheirThreadParms = (FT_CALL_THREAD_PARMS*)
        malloc ( sizeof ( FT_CALL_THREAD_PARMS ) );

    if ( !pCallTheirThreadParms )
    {
        logmsg("fthread_create: malloc(FT_CALL_THREAD_PARMS) failed\n");
        return RC(ENOMEM);      // (out of memory)
    }

    pFTHREAD = (FTHREAD*)
        malloc ( sizeof( FTHREAD ) );

    if ( !pFTHREAD )
    {
        logmsg("fthread_create: malloc(FTHREAD) failed\n");
        free ( pCallTheirThreadParms );
        return RC(ENOMEM);      // (out of memory)
    }

    pCallTheirThreadParms->pfnTheirThreadFunc = pfnThreadFunc;
    pCallTheirThreadParms->pvTheirThreadArgs  = pvThreadArgs;
    pCallTheirThreadParms->pszTheirThreadName = pszThreadName;
    pCallTheirThreadParms->pFTHREAD           = pFTHREAD;

    InitializeListLink(&pFTHREAD->ThreadListLink);

    pFTHREAD->dwThreadID    = 0;
    pFTHREAD->hThreadHandle = NULL;
    pFTHREAD->bJoinable     = ((FTHREAD_CREATE_JOINABLE == nDetachState) ? (TRUE) : (FALSE));
    pFTHREAD->nJoinedCount  = 0;
    pFTHREAD->ExitVal       = NULL;

    LockThreadsList();

    hThread =
        MyCreateThread ( NULL, nStackSize, FTWin32ThreadFunc, pCallTheirThreadParms, 0, &dwThreadID );

    if ( !hThread )
    {
        UnlockThreadsList();
        logmsg("fthread_create: MyCreateThread failed\n");
        free ( pCallTheirThreadParms );
        free ( pFTHREAD );
        return RC(EAGAIN);      // (unable to obtain required resources)
    }

    pFTHREAD->hThreadHandle = hThread;
    pFTHREAD->dwThreadID    = dwThreadID;
    *pdwThreadID            = dwThreadID;

    InsertListHead ( &ThreadListHead, &pFTHREAD->ThreadListLink );

    UnlockThreadsList();

    return RC(0);
}

////////////////////////////////////////////////////////////////////////////////////
// Exit from a thread...

DLL_EXPORT
void  fthread_exit
(
    void*  ExitVal
)
{
    FTHREAD* pFTHREAD;
    VERIFY ( pFTHREAD = FindFTHREAD ( GetCurrentThreadId() ) );
    pFTHREAD->ExitVal = ExitVal;
    UnlockThreadsList();
    longjmp ( pFTHREAD->JumpBuf, 1 );
}

////////////////////////////////////////////////////////////////////////////////////
// Join a thread (i.e. wait for a thread's termination)...

DLL_EXPORT
int  fthread_join
(
    fthread_t       dwThreadID,
    void**          pExitVal
)
{
    HANDLE    hThread;
    FTHREAD*  pFTHREAD;

    if ( GetCurrentThreadId() == dwThreadID )
        return RC(EDEADLK);             // (can't join self!)

    if ( !(pFTHREAD = FindFTHREAD ( dwThreadID ) ) )
        return RC(ESRCH);               // (thread not found)

    // (Note: threads list lock still held at this point
    //  since thread was found...)

    if ( !pFTHREAD->bJoinable )
    {
        UnlockThreadsList();
        return RC(EINVAL);              // (not a joinable thread)
    }

    ASSERT ( pFTHREAD->nJoinedCount >= 0 );
    pFTHREAD->nJoinedCount++;
    hThread = pFTHREAD->hThreadHandle;

    // Wait for thread to exit...

    UnlockThreadsList();
    {
        WaitForSingleObject ( hThread, INFINITE );
    }
    LockThreadsList();

    if ( pExitVal )
        *pExitVal = pFTHREAD->ExitVal;  // (pass back thread's exit value)

    ASSERT ( pFTHREAD->nJoinedCount > 0 );
    pFTHREAD->nJoinedCount--;

    // If this is the last thread to be resumed after having been suspended
    // (as a result of doing the join), then we need to do the detach (i.e.
    // to free resources), BUT ONLY IF the detach for the thread in question
    // has already been done by someone (which can be determined by virtue of
    // the "joinable" flag having already been changed back to non-joinable).

    // The idea here is that the 'detach' function purposely does not free
    // the resources unless the 'joined' count is zero. If the joined count
    // is NOT zero whenever the detach function is called, then the resources
    // cannot be freed since there's still a thread waiting to be resumed
    // from its join (perhaps us!), and it obviously still needs access to
    // the resources in question. Thus, in such a situation (i.e. there still
    // being a thread remaining to be woken up from its join when the detach
    // is done), the freeing of resources normally done by the detach function
    // is deferred so that WE can do the resource freeing ourselves once we
    // are done with them.

    if ( !pFTHREAD->bJoinable && pFTHREAD->nJoinedCount <= 0 )
    {
        CloseHandle ( pFTHREAD->hThreadHandle );
        RemoveListEntry ( &pFTHREAD->ThreadListLink );
        free ( pFTHREAD );
    }

    UnlockThreadsList();

    return RC(0);
}

////////////////////////////////////////////////////////////////////////////////////
// Detach a thread (i.e. ignore a thread's termination)...

DLL_EXPORT
int  fthread_detach
(
    fthread_t  dwThreadID
)
{
    FTHREAD*  pFTHREAD;

    if ( !( pFTHREAD = FindFTHREAD ( dwThreadID ) ) )
        return RC(ESRCH);           // (thread not found)

    // (Note: threads list lock still held at this point
    //  since thread was found...)

    if ( !pFTHREAD->bJoinable )
    {
        UnlockThreadsList();
        return RC(EINVAL);          // (not a joinable thread)
    }

    // If the thread has not yet exited, then IT will free its
    // own resources itself whenever it eventually does exit by
    // virtue of our changing it to a non-joinable thread type.

    pFTHREAD->bJoinable = FALSE;    // (indicate detach was done)

    // Otherwise we need to free its resources ourselves since
    // it obviously can't (since it has already exited).

    // Note that we cannot free the resources ourselves even if the
    // thread has already exited if there are still other threads
    // waiting to be woken up from their own join (since they will
    // still need to have access to the resources). In other words,
    // even if the thread has already exited (and thus it would seem
    // that our freeing the resources would be the proper thing to
    // do), we CANNOT do so if the 'join' count is non-zero.

    // In such a situation (the join count being non-zero indicating
    // there is still another thread waiting to be resumed from its
    // own join), we simply defer the actual freeing of resources to
    // the thread still waiting to be woken up from its join. Whenever
    // it does eventually wake up from its join, it will free the
    // resources for us, as long as we remember to reset the 'joinable'
    // flag back to non-joinable (which we've already done just above).

    if ( IsEventSet ( pFTHREAD->hThreadHandle ) && pFTHREAD->nJoinedCount <= 0 )
    {
        CloseHandle ( pFTHREAD->hThreadHandle );
        RemoveListEntry ( &pFTHREAD->ThreadListLink );
        free ( pFTHREAD );
    }

    UnlockThreadsList();

    return RC(0);
}

////////////////////////////////////////////////////////////////////////////////////
// Initialize a "thread attribute"...

DLL_EXPORT
int  fthread_attr_init
(
    fthread_attr_t*  pThreadAttr
)
{
    if ( !pThreadAttr )
        return RC(EINVAL);          // (invalid ptr)

    if ( FT_ATTR_MAGIC == pThreadAttr->dwAttrMagic )
        return RC(EBUSY);           // (already initialized)

    pThreadAttr->dwAttrMagic  = FT_ATTR_MAGIC;
    pThreadAttr->nDetachState = FTHREAD_CREATE_DEFAULT;
    pThreadAttr->nStackSize   = 0;

    return RC(0);
}

////////////////////////////////////////////////////////////////////////////////////
// Destroy a "thread attribute"...

DLL_EXPORT
int  fthread_attr_destroy
(
    fthread_attr_t*  pThreadAttr
)
{
    if ( !pThreadAttr )
        return RC(EINVAL);      // (invalid ptr)

    if ( FT_ATTR_MAGIC != pThreadAttr->dwAttrMagic )
        return RC(EINVAL);      // (not initialized)

    pThreadAttr->dwAttrMagic  = 0;
    pThreadAttr->nDetachState = 0;
    pThreadAttr->nStackSize   = 0;

    return RC(0);
}

////////////////////////////////////////////////////////////////////////////////////
// Set a thread's "detachstate" attribute...

DLL_EXPORT
int  fthread_attr_setdetachstate
(
    fthread_attr_t*  pThreadAttr,
    int              nDetachState
)
{
    if ( !pThreadAttr )
        return RC(EINVAL);          // (invalid ptr)

    if ( FT_ATTR_MAGIC != pThreadAttr->dwAttrMagic )
        return RC(EINVAL);          // (not initialized)

    if ( FTHREAD_CREATE_DETACHED != nDetachState &&
         FTHREAD_CREATE_JOINABLE != nDetachState )
        return RC(EINVAL);          // (invalid detach state)

    pThreadAttr->nDetachState = nDetachState;

    return RC(0);
}

////////////////////////////////////////////////////////////////////////////////////
// Retrieve a thread's "detachstate" attribute...

DLL_EXPORT
int  fthread_attr_getdetachstate
(
    const fthread_attr_t*  pThreadAttr,
    int*                   pnDetachState
)
{
    if ( !pThreadAttr || !pnDetachState )
        return RC(EINVAL);          // (invalid ptr)

    if ( FT_ATTR_MAGIC != pThreadAttr->dwAttrMagic )
        return RC(EINVAL);          // (not initialized)

    if ( FTHREAD_CREATE_DETACHED != pThreadAttr->nDetachState &&
         FTHREAD_CREATE_JOINABLE != pThreadAttr->nDetachState )
        return RC(EINVAL);          // (invalid detach state)

    *pnDetachState = pThreadAttr->nDetachState;

    return RC(0);
}

////////////////////////////////////////////////////////////////////////////////////
// Set a thread's initial stack size...

DLL_EXPORT
int  fthread_attr_setstacksize
(
    fthread_attr_t*  pThreadAttr,
    size_t           nStackSize
)
{
    if ( !pThreadAttr )
        return RC(EINVAL);          // (invalid ptr)

    if ( FT_ATTR_MAGIC != pThreadAttr->dwAttrMagic )
        return RC(EINVAL);          // (not initialized)

    pThreadAttr->nStackSize = nStackSize;

    return RC(0);
}

////////////////////////////////////////////////////////////////////////////////////
// Retrieve a thread's initial stack size...

DLL_EXPORT
int  fthread_attr_getstacksize
(
    const fthread_attr_t*  pThreadAttr,
    size_t*                pnStackSize
)
{
    if ( !pThreadAttr || !pnStackSize )
        return RC(EINVAL);          // (invalid ptr)

    if ( FT_ATTR_MAGIC != pThreadAttr->dwAttrMagic )
        return RC(EINVAL);          // (not initialized)

    *pnStackSize = pThreadAttr->nStackSize;

    return RC(0);
}

////////////////////////////////////////////////////////////////////////////////////
// (thread signalling not [currently] supported (yet); always returns ENOTSUP...)

DLL_EXPORT
int  fthread_kill       // FIXME: TODO:
(
    int  dummy1,
    int  dummy2
)
{
    UNREFERENCED ( dummy1 );
    UNREFERENCED ( dummy2 );
    return RC(ENOTSUP);
}

////////////////////////////////////////////////////////////////////////////////////
// Return thread-id...

DLL_EXPORT
fthread_t  fthread_self ()
{
    return GetCurrentThreadId();
}

////////////////////////////////////////////////////////////////////////////////////
// Compare thread-ids...

DLL_EXPORT
int  fthread_equal
(
    fthread_t  pdwThreadID_1,
    fthread_t  pdwThreadID_2
)
{
    return ( pdwThreadID_1 == pdwThreadID_2 );
}

////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
// Initialize a lock...

DLL_EXPORT
int  fthread_mutex_init
(
          fthread_mutex_t*      pFTUSER_MUTEX,
    const fthread_mutexattr_t*  pFT_MUTEX_ATTR
)
{
    DWORD  dwMutexType = 0;

    if ( !pFTUSER_MUTEX )
        return RC(EINVAL);      // (invalid mutex ptr)

    if ( FT_MUTEX_MAGIC == pFTUSER_MUTEX->dwMutexMagic )
        return RC(EBUSY);       // (mutex already initialized)

    if ( pFT_MUTEX_ATTR && !IsValidMutexType ( dwMutexType = *pFT_MUTEX_ATTR ) )
        return RC(EINVAL);      // (invalid mutex attr ptr or mutex attr type)

    if ( !(pFTUSER_MUTEX->hMutex = MallocFT_MUTEX()) )
        return RC(ENOMEM);      // (out of memory)

    if ( !InitializeFT_MUTEX
    (
        pFTUSER_MUTEX->hMutex,
        pFT_MUTEX_ATTR ? dwMutexType : FTHREAD_MUTEX_DEFAULT
    ))
    {
        free ( pFTUSER_MUTEX->hMutex );

        pFTUSER_MUTEX->dwMutexMagic = 0;
        pFTUSER_MUTEX->hMutex       = NULL;

        return RC(EAGAIN);      // (unable to obtain required resources)
    }

    pFTUSER_MUTEX->dwMutexMagic = FT_MUTEX_MAGIC;

    return RC(0);
}

////////////////////////////////////////////////////////////////////////////////////
// Destroy a lock...

DLL_EXPORT
int  fthread_mutex_destroy
(
    fthread_mutex_t*  pFTUSER_MUTEX
)
{
    if ( !pFTUSER_MUTEX )
        return RC(EINVAL);      // (invalid ptr)

    if ( FT_MUTEX_MAGIC != pFTUSER_MUTEX->dwMutexMagic )
        return RC(EINVAL);      // (not initialized)

    if ( !UninitializeFT_MUTEX
    (
        pFTUSER_MUTEX->hMutex
    ))
        return RC(EBUSY);       // (still in use)

    free ( pFTUSER_MUTEX->hMutex );

    pFTUSER_MUTEX->dwMutexMagic = 0;
    pFTUSER_MUTEX->hMutex       = NULL;

    return RC(0);
}

////////////////////////////////////////////////////////////////////////////////////
// Try to lock a "mutex"...

DLL_EXPORT
int  fthread_mutex_trylock
(
    fthread_mutex_t*  pFTUSER_MUTEX
)
{
    if ( !pFTUSER_MUTEX )
        return RC(EINVAL);      // (invalid ptr)

    if ( FT_MUTEX_MAGIC != pFTUSER_MUTEX->dwMutexMagic )
        return RC(EINVAL);      // (not initialized)

    // Try to acquire the requested mutex...

    if
    (
        !TryEnterFT_MUTEX
        (
            pFTUSER_MUTEX->hMutex
        )
    )
        // We could not acquire the mutex; return 'busy'...

        return RC(EBUSY);

    // We successfully acquired the mutex... If the mutex type is recursive,
    // or, if not recursive (i.e. error-check), if this was the first/initial
    // lock on the mutex, then return success...

    if (0
        || FTHREAD_MUTEX_RECURSIVE == ((FT_MUTEX*)pFTUSER_MUTEX->hMutex)->dwMutexType
        || ((FT_MUTEX*)pFTUSER_MUTEX->hMutex)->nLockedCount <= 1
    )
        return RC(0);

    ASSERT ( FTHREAD_MUTEX_ERRORCHECK == ((FT_MUTEX*)pFTUSER_MUTEX->hMutex)->dwMutexType
        && ((FT_MUTEX*)pFTUSER_MUTEX->hMutex)->nLockedCount > 1 );

    // The mutex type is error-check and we already previously had the mutex locked
    // before (i.e. this was the *second* time we acquired this same mutex). Return
    // 'busy' after first releasing the mutex once (to decrement the locked count
    // back down to what it was (i.e. 1 (one))).

    LeaveFT_MUTEX
    (
        pFTUSER_MUTEX->hMutex
    );

    return RC(EBUSY);
}

////////////////////////////////////////////////////////////////////////////////////
// Lock a "mutex"...

DLL_EXPORT
int  fthread_mutex_lock
(
    fthread_mutex_t*  pFTUSER_MUTEX
)
{
    if ( !pFTUSER_MUTEX )
        return RC(EINVAL);      // (invalid ptr)

    if ( FT_MUTEX_MAGIC != pFTUSER_MUTEX->dwMutexMagic )
        return RC(EINVAL);      // (not initialized)

    // Try to acquire the requested mutex...

    if
    (
        !TryEnterFT_MUTEX
        (
            pFTUSER_MUTEX->hMutex
        )
    )
    {
        // We could not acquire the mutex. This means someone already owns the mutex,
        // so just do a normal acquire on the mutex. Both recursive and error-check
        // types will block until such time as the mutex is successfully acquired...

        EnterFT_MUTEX
        (
            pFTUSER_MUTEX->hMutex
        );

        return RC(0);
    }

    // We successfully acquired the mutex... If the mutex type is recursive,
    // or, if not recursive (i.e. error-check), if this was the first/initial
    // lock on the mutex, then return success...

    if (0
        || FTHREAD_MUTEX_RECURSIVE == ((FT_MUTEX*)pFTUSER_MUTEX->hMutex)->dwMutexType
        || ((FT_MUTEX*)pFTUSER_MUTEX->hMutex)->nLockedCount <= 1
    )
        return RC(0);

    ASSERT ( FTHREAD_MUTEX_ERRORCHECK == ((FT_MUTEX*)pFTUSER_MUTEX->hMutex)->dwMutexType
        && ((FT_MUTEX*)pFTUSER_MUTEX->hMutex)->nLockedCount > 1 );

    // The mutex type is error-check and we already previously had the mutex locked
    // before (i.e. this was the *second* time we acquired this same mutex). Return
    // 'deadlock' after first releasing the mutex once (to decrement the locked count
    // back down to what it was (i.e. 1 (one))).

    LeaveFT_MUTEX
    (
        pFTUSER_MUTEX->hMutex
    );

    return RC(EDEADLK);
}

////////////////////////////////////////////////////////////////////////////////////
// Unlock a "mutex"...

DLL_EXPORT
int  fthread_mutex_unlock
(
    fthread_mutex_t*  pFTUSER_MUTEX
)
{
    if (0
        || !pFTUSER_MUTEX                                   // (invalid ptr)
        ||   FT_MUTEX_MAGIC != pFTUSER_MUTEX->dwMutexMagic  // (not initialized)
    )
        return RC(EINVAL);

    if (0
        || GetCurrentThreadId() != ((PFT_MUTEX)pFTUSER_MUTEX->hMutex)->dwLockOwner  // (not owned)
        || ((PFT_MUTEX)pFTUSER_MUTEX->hMutex)->nLockedCount <= 0                    // (not locked)
    )
        return RC(EPERM);

    ASSERT ( ((FT_MUTEX*)pFTUSER_MUTEX->hMutex)->nLockedCount <= 1
        || FTHREAD_MUTEX_RECURSIVE == ((FT_MUTEX*)pFTUSER_MUTEX->hMutex)->dwMutexType );

    LeaveFT_MUTEX
    (
        pFTUSER_MUTEX->hMutex
    );

    return RC(0);
}

////////////////////////////////////////////////////////////////////////////////////
// Initialize a "condition"...

DLL_EXPORT
int  fthread_cond_init
(
    fthread_cond_t*  pFT_COND_VAR
)
{
    if ( !pFT_COND_VAR )
        return RC(EINVAL);      // (invalid ptr)

    if ( FT_COND_MAGIC == pFT_COND_VAR->dwCondMagic )
        return RC(EBUSY);       // (already initialized)

    if ( !(pFT_COND_VAR->hCondVar = MallocFT_COND_VAR()) )
        return RC(ENOMEM);      // (out of memory)

    if ( !InitializeFT_COND_VAR
    (
        pFT_COND_VAR->hCondVar
    ))
    {
        free ( pFT_COND_VAR->hCondVar );

        pFT_COND_VAR->dwCondMagic = 0;
        pFT_COND_VAR->hCondVar    = NULL;

        return RC(EAGAIN);      // (unable to obtain required resources)
    }

    pFT_COND_VAR->dwCondMagic = FT_COND_MAGIC;

    return RC(0);
}

////////////////////////////////////////////////////////////////////////////////////
// Destroy a "condition"...

DLL_EXPORT
int  fthread_cond_destroy
(
    fthread_cond_t*  pFT_COND_VAR
)
{
    if ( !pFT_COND_VAR )
        return RC(EINVAL);      // (invalid ptr)

    if ( FT_COND_MAGIC != pFT_COND_VAR->dwCondMagic )
        return RC(EINVAL);      // (not initialized)

    if ( !UninitializeFT_COND_VAR
    (
        pFT_COND_VAR->hCondVar
    ))
        return RC(EBUSY);       // (still in use)

    free ( pFT_COND_VAR->hCondVar );

    pFT_COND_VAR->dwCondMagic = 0;
    pFT_COND_VAR->hCondVar    = NULL;

    return RC(0);
}

////////////////////////////////////////////////////////////////////////////////////
// 'Signal' a "condition"...     (causes ONE waiting thread to be released)

DLL_EXPORT
int  fthread_cond_signal
(
    fthread_cond_t*  pFT_COND_VAR
)
{
    if ( !pFT_COND_VAR )
        return RC(EINVAL);      // (invalid ptr)

    if ( FT_COND_MAGIC != pFT_COND_VAR->dwCondMagic )
        return RC(EINVAL);      // (not initialized)

    return QueueTransmission
    (
        pFT_COND_VAR->hCondVar,
        FALSE               // (FALSE == not "broadcast")
    );
}

////////////////////////////////////////////////////////////////////////////////////
// 'Broadcast' a "condition"...  (causes ALL waiting threads to be released)

DLL_EXPORT
int  fthread_cond_broadcast
(
    fthread_cond_t*  pFT_COND_VAR
)
{
    if ( !pFT_COND_VAR )
        return RC(EINVAL);      // (invalid ptr)

    if ( FT_COND_MAGIC != pFT_COND_VAR->dwCondMagic )
        return RC(EINVAL);      // (not initialized)

    return QueueTransmission
    (
        pFT_COND_VAR->hCondVar,
        TRUE                // (TRUE == "broadcast" type)
    );
}

////////////////////////////////////////////////////////////////////////////////////
// Wait for a "condition" to occur...

DLL_EXPORT
int  fthread_cond_wait
(
    fthread_cond_t*   pFT_COND_VAR,
    fthread_mutex_t*  pFTUSER_MUTEX
)
{
    int rc;

    if (0
        || !pFT_COND_VAR                                        // (invalid ptr)
        ||   FT_COND_MAGIC  != pFT_COND_VAR  -> dwCondMagic     // (not initialized)
        || !pFTUSER_MUTEX                                       // (invalid ptr)
        ||   FT_MUTEX_MAGIC != pFTUSER_MUTEX -> dwMutexMagic    // (not initialized)
    )
        return RC(EINVAL);

    // The following call essentially atomically releases the caller's mutex
    // and does a wait. Of course, it doesn't really do the wait though; that's
    // actually done further below. BUT, it does atomically register the fact
    // that this thread *wishes* to do a wait by acquiring the condition variable
    // lock and then incrementing the #of waiters counter before it releases the
    // original mutex. Thus, whenever the below function call returns back to us,
    // we can be assured that: 1) our request to wait on this condition variable
    // has been registered AND 2) we have control of the condition variable in
    // question (i.e. we still hold the condition variable lock thus preventing
    // anyone from trying to send a signal just yet)...

    if
    (
        (
            rc = BeginWait
            (
                pFT_COND_VAR -> hCondVar,
                pFTUSER_MUTEX
            )
        )
        != 0
    )
    {
        // OOPS! Something went wrong. The original mutex has NOT been released
        // and we did NOT acquire our condition variable lock (and thus our wait
        // was not registered). Thus we can safely return back to the caller with
        // the original mutex still owned (held) by the caller.

        return RC(rc); // (return error code to caller; their wait failed)
    }

    // We only reach here if the condition var was successfully acquired AND our
    // wait was registered AND the original mutex was released so the signal can
    // be sent (but the signal (transmission) of course cannot ever be sent until
    // we first release our lock on our condition variable, which is of course is
    // what the below WaitForTransmission function call does within its wait loop)...

    rc = WaitForTransmission    // (wait for "signal" or "broadcast"...)
    (
        pFT_COND_VAR->hCondVar,
        NULL
    );

    // A signal (transmission) was sent and we're one of the ones (or the
    // only one) that's supposed to receive it...

    // If we're the only one that's supposed to receive this transmission,
    // then we need to turn off the transmitter (stop "sending" the signal)
    // so that no other threads get "woken up" (released) as a result of
    // this particular "signal" (transmission)...

    // (Note that the below call also de-registers our wait too)

    ReceiveXmission         // (reset transmitter)
    (
        pFT_COND_VAR->hCondVar
    );

    // Release the condition var lock (since we're done with it) and then
    // reacquire the caller's original mutex (if possible) and then return
    // back to the original caller with their original mutex held with what-
    // ever return code got set by the above wait call...

    return ReturnFromWait
    (
        pFT_COND_VAR -> hCondVar,
        pFTUSER_MUTEX,
        rc
    );
}

////////////////////////////////////////////////////////////////////////////////////
// Wait (but not forever) for a "condition" to occur...

// Refer to the comments in the above 'fthread_cond_wait' function (as well as all
// of our other internal functions too of course (BeginWait, WaitForTransmission,
// ReceiveXmission and ReturnFromWait)) for details regarding what's going on here
// (i.e. what we're doing below and why). The below function is essentially identical
// to the above 'fthread_cond_wait' function except that we don't wait forever; we
// only wait for a limited amount of time. Other than that they're exactly identical
// so there's no sense in repeating myself here...

DLL_EXPORT
int  fthread_cond_timedwait
(
    fthread_cond_t*   pFT_COND_VAR,
    fthread_mutex_t*  pFTUSER_MUTEX,
    struct timespec*  pTimeTimeout
)
{
    int rc;

    if (0
        || !pFT_COND_VAR
        ||   FT_COND_MAGIC  != pFT_COND_VAR -> dwCondMagic
        || !pFTUSER_MUTEX
        ||   FT_MUTEX_MAGIC != pFTUSER_MUTEX    -> dwMutexMagic
        || !pTimeTimeout
    )
        return RC(EINVAL);

    if
    (
        (
            rc = BeginWait
            (
                pFT_COND_VAR -> hCondVar,
                pFTUSER_MUTEX
            )
        )
        != 0
    )
        return rc;

    rc = WaitForTransmission
    (
        pFT_COND_VAR->hCondVar,
        pTimeTimeout
    );

    ReceiveXmission
    (
        pFT_COND_VAR->hCondVar
    );

    return ReturnFromWait
    (
        pFT_COND_VAR -> hCondVar,
        pFTUSER_MUTEX,
        rc
    );
}

////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
// Initialize a "mutex" attribute...

DLL_EXPORT
int  fthread_mutexattr_init ( fthread_mutexattr_t*  pFT_MUTEX_ATTR )
{
    if ( !pFT_MUTEX_ATTR )
        return RC(EINVAL);
    *pFT_MUTEX_ATTR = FTHREAD_MUTEX_DEFAULT;
    return RC(0);
}

////////////////////////////////////////////////////////////////////////////////////
// Destroy a "mutex" attribute...

DLL_EXPORT
int  fthread_mutexattr_destroy ( fthread_mutexattr_t*  pFT_MUTEX_ATTR )
{
    if ( !pFT_MUTEX_ATTR )
        return RC(EINVAL);
    *pFT_MUTEX_ATTR = 0xCDCDCDCD;
    return RC(0);
}

////////////////////////////////////////////////////////////////////////////////////
// Retrieve "mutex" attribute type...

DLL_EXPORT
int fthread_mutexattr_gettype
(
    const fthread_mutexattr_t*  pFT_MUTEX_ATTR,
    int*                        pnMutexType
)
{
    DWORD  dwMutexType;
    if ( !pFT_MUTEX_ATTR || !pnMutexType || !IsValidMutexType ( dwMutexType = *pFT_MUTEX_ATTR ) )
        return RC(EINVAL);
    *pnMutexType = (int) dwMutexType;
    return RC(0);
}

////////////////////////////////////////////////////////////////////////////////////
// Set "mutex" attribute type...

DLL_EXPORT
int fthread_mutexattr_settype
(
    fthread_mutexattr_t*  pFT_MUTEX_ATTR,
    int                   nMutexType
)
{
    if ( !pFT_MUTEX_ATTR || !IsValidMutexType ( (DWORD) nMutexType ) )
        return RC(EINVAL);
    *pFT_MUTEX_ATTR = (DWORD) nMutexType;
    return RC(0);
}

////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////

#endif // !defined(OPTION_FTHREADS)