File: processes.cpp

package info (click to toggle)
polyml 5.7.1-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid
  • size: 40,616 kB
  • sloc: cpp: 44,142; ansic: 26,963; sh: 22,002; asm: 13,486; makefile: 602; exp: 525; python: 253; awk: 91
file content (2378 lines) | stat: -rw-r--r-- 84,661 bytes parent folder | download | duplicates (3)
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
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
/*
    Title:      Thread functions
    Author:     David C.J. Matthews

    Copyright (c) 2007,2008,2013-15, 2017 David C.J. Matthews

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License version 2.1 as published by the Free Software Foundation.
    
    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.
    
    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

*/

#ifdef HAVE_CONFIG_H
#include "config.h"
#elif defined(_WIN32)
#include "winconfig.h"
#else
#error "No configuration file"
#endif

#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif

#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif

#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif

#ifdef HAVE_STRING_H
#include <string.h>
#endif

#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif

#ifdef HAVE_ASSERT_H
#include <assert.h>
#define ASSERT(x) assert(x)
#else
#define ASSERT(x)
#endif

#ifdef HAVE_PROCESS_H
#include <process.h>
#endif

#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif

#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif

#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif

#ifdef HAVE_UNISTD_H
#include <unistd.h> // Want unistd for _SC_NPROCESSORS_ONLN at least
#endif

#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif

#ifdef HAVE_WINDOWS_H
#include <windows.h>
#endif

#if ((!defined(_WIN32) || defined(__CYGWIN__)) && defined(HAVE_LIBPTHREAD) && defined(HAVE_PTHREAD_H))
#define HAVE_PTHREAD 1
#include <pthread.h>
#endif

#ifdef HAVE_SYS_SYSCTL_H
// Used determine number of processors in Mac OS X.
#include <sys/sysctl.h>
#endif

#if (defined(_WIN32) && ! defined(__CYGWIN__))
#include <tchar.h>
#endif

#include <new>

/************************************************************************
 *
 * Include runtime headers
 *
 ************************************************************************/

#include "globals.h"
#include "gc.h"
#include "mpoly.h"
#include "arb.h"
#include "machine_dep.h"
#include "diagnostics.h"
#include "processes.h"
#include "run_time.h"
#include "sys.h"
#include "sighandler.h"
#include "scanaddrs.h"
#include "save_vec.h"
#include "rts_module.h"
#include "noreturn.h"
#include "memmgr.h"
#include "locking.h"
#include "profiling.h"
#include "sharedata.h"
#include "exporter.h"
#include "statistics.h"
#include "rtsentry.h"

#if (defined(_WIN32) && ! defined(__CYGWIN__))
#include "Console.h"
#endif

extern "C" {
    POLYEXTERNALSYMBOL POLYUNSIGNED PolyThreadGeneral(PolyObject *threadId, PolyWord code, PolyWord arg);
    POLYEXTERNALSYMBOL POLYUNSIGNED PolyThreadKillSelf(PolyObject *threadId);
    POLYEXTERNALSYMBOL POLYUNSIGNED PolyThreadMutexBlock(PolyObject *threadId, PolyWord arg);
    POLYEXTERNALSYMBOL POLYUNSIGNED PolyThreadMutexUnlock(PolyObject *threadId, PolyWord arg);
    POLYEXTERNALSYMBOL POLYUNSIGNED PolyThreadCondVarWait(PolyObject *threadId, PolyWord arg);
    POLYEXTERNALSYMBOL POLYUNSIGNED PolyThreadCondVarWaitUntil(PolyObject *threadId, PolyWord lockArg, PolyWord timeArg);
    POLYEXTERNALSYMBOL POLYUNSIGNED PolyThreadCondVarWake(PolyWord targetThread);
    POLYEXTERNALSYMBOL POLYUNSIGNED PolyThreadForkThread(PolyObject *threadId, PolyWord function, PolyWord attrs, PolyWord stack);
    POLYEXTERNALSYMBOL POLYUNSIGNED PolyThreadIsActive(PolyWord targetThread);
    POLYEXTERNALSYMBOL POLYUNSIGNED PolyThreadInterruptThread(PolyWord targetThread);
    POLYEXTERNALSYMBOL POLYUNSIGNED PolyThreadKillThread(PolyWord targetThread);
    POLYEXTERNALSYMBOL POLYUNSIGNED PolyThreadBroadcastInterrupt();
    POLYEXTERNALSYMBOL POLYUNSIGNED PolyThreadTestInterrupt(PolyWord threadId);
    POLYEXTERNALSYMBOL POLYUNSIGNED PolyThreadNumProcessors();
    POLYEXTERNALSYMBOL POLYUNSIGNED PolyThreadNumPhysicalProcessors();
    POLYEXTERNALSYMBOL POLYUNSIGNED PolyThreadMaxStackSize(PolyObject *threadId, PolyWord newSize);
}

#define SAVE(x) taskData->saveVec.push(x)
#define SIZEOF(x) (sizeof(x)/sizeof(PolyWord))

// These values are stored in the second word of thread id object as
// a tagged integer.  They may be set and read by the thread in the ML
// code.  
#define PFLAG_BROADCAST     1   // If set, accepts a broadcast
// How to handle interrrupts
#define PFLAG_IGNORE        0   // Ignore interrupts completely
#define PFLAG_SYNCH         2   // Handle synchronously
#define PFLAG_ASYNCH        4   // Handle asynchronously
#define PFLAG_ASYNCH_ONCE   6   // First handle asynchronously then switch to synch.
#define PFLAG_INTMASK       6   // Mask of the above bits

struct _entrypts processesEPT[] =
{
    { "PolyThreadGeneral",              (polyRTSFunction)&PolyThreadGeneral},
    { "PolyThreadKillSelf",             (polyRTSFunction)&PolyThreadKillSelf},
    { "PolyThreadMutexBlock",           (polyRTSFunction)&PolyThreadMutexBlock},
    { "PolyThreadMutexUnlock",          (polyRTSFunction)&PolyThreadMutexUnlock},
    { "PolyThreadCondVarWait",          (polyRTSFunction)&PolyThreadCondVarWait},
    { "PolyThreadCondVarWaitUntil",     (polyRTSFunction)&PolyThreadCondVarWaitUntil},
    { "PolyThreadCondVarWake",          (polyRTSFunction)&PolyThreadCondVarWake},
    { "PolyThreadForkThread",           (polyRTSFunction)&PolyThreadForkThread},
    { "PolyThreadIsActive",             (polyRTSFunction)&PolyThreadIsActive},
    { "PolyThreadInterruptThread",      (polyRTSFunction)&PolyThreadInterruptThread},
    { "PolyThreadKillThread",           (polyRTSFunction)&PolyThreadKillThread},
    { "PolyThreadBroadcastInterrupt",   (polyRTSFunction)&PolyThreadBroadcastInterrupt},
    { "PolyThreadTestInterrupt",        (polyRTSFunction)&PolyThreadTestInterrupt},
    { "PolyThreadNumProcessors",        (polyRTSFunction)&PolyThreadNumProcessors},
    { "PolyThreadNumPhysicalProcessors",(polyRTSFunction)&PolyThreadNumPhysicalProcessors},
    { "PolyThreadMaxStackSize",         (polyRTSFunction)&PolyThreadMaxStackSize},

    { NULL, NULL} // End of list.
};

class Processes: public ProcessExternal, public RtsModule
{
public:
    Processes();
    virtual void Init(void);
    virtual void Stop(void);
    void GarbageCollect(ScanAddress *process);
public:
    void BroadcastInterrupt(void);
    void BeginRootThread(PolyObject *rootFunction);
    void Exit(int n); // Request all ML threads to exit and set the process result code.
    // Called when a thread has completed - doesn't return.
    virtual NORETURNFN(void ThreadExit(TaskData *taskData));

    // Called when a thread may block.  Returns some time later when perhaps
    // the input is available.
    virtual void ThreadPauseForIO(TaskData *taskData, Waiter *pWait);
    // Return the task data for the current thread.
    virtual TaskData *GetTaskDataForThread(void);
    // Create a new task data object for the current thread.
    virtual TaskData *CreateNewTaskData(Handle threadId, Handle threadFunction,
                           Handle args, PolyWord flags);
    // ForkFromRTS.  Creates a new thread from within the RTS.
    virtual bool ForkFromRTS(TaskData *taskData, Handle proc, Handle arg);
    // Create a new thread.  The "args" argument is only used for threads
    // created in the RTS by the signal handler.
    Handle ForkThread(TaskData *taskData, Handle threadFunction,
                    Handle args, PolyWord flags, PolyWord stacksize);
    // Process general RTS requests from ML.
    Handle ThreadDispatch(TaskData *taskData, Handle args, Handle code);

    virtual void ThreadUseMLMemory(TaskData *taskData); 
    virtual void ThreadReleaseMLMemory(TaskData *taskData);

    virtual poly_exn* GetInterrupt(void) { return interrupt_exn; }

    // If the schedule lock is already held we need to use these functions.
    void ThreadUseMLMemoryWithSchedLock(TaskData *taskData);
    void ThreadReleaseMLMemoryWithSchedLock(TaskData *taskData);

    // Requests from the threads for actions that need to be performed by
    // the root thread. Make the request and wait until it has completed.
    virtual void MakeRootRequest(TaskData *taskData, MainThreadRequest *request);

    // Deal with any interrupt or kill requests.
    virtual bool ProcessAsynchRequests(TaskData *taskData);
    // Process an interrupt request synchronously.
    virtual void TestSynchronousRequests(TaskData *taskData);
    // Process any events, synchronous or asynchronous.
    virtual void TestAnyEvents(TaskData *taskData);

    // Set a thread to be interrupted or killed.  Wakes up the
    // thread if necessary.  MUST be called with schedLock held.
    void MakeRequest(TaskData *p, ThreadRequests request);

    // Profiling control.
    virtual void StartProfiling(void);
    virtual void StopProfiling(void);

#ifdef HAVE_WINDOWS_H
    // Windows: Called every millisecond while profiling is on.
    void ProfileInterrupt(void);
#else
    // Unix: Start a profile timer for a thread.
    void StartProfilingTimer(void);
#endif
    // Memory allocation.  Tries to allocate space.  If the allocation succeeds it
    // may update the allocation values in the taskData object.  If the heap is exhausted
    // it may set this thread (or other threads) to raise an exception.
    PolyWord *FindAllocationSpace(TaskData *taskData, POLYUNSIGNED words, bool alwaysInSeg);

    // Find a task that matches the specified identifier and returns
    // it if it exists.  MUST be called with schedLock held.
    TaskData *TaskForIdentifier(PolyObject *taskId);

    // Signal handling support.  The ML signal handler thread blocks until it is
    // woken up by the signal detection thread.
    virtual bool WaitForSignal(TaskData *taskData, PLock *sigLock);
    virtual void SignalArrived(void);

    virtual void SetSingleThreaded(void) { singleThreaded = true; }

    // Operations on mutexes
    void MutexBlock(TaskData *taskData, Handle hMutex);
    void MutexUnlock(TaskData *taskData, Handle hMutex);

    // Operations on condition variables.
    void WaitInfinite(TaskData *taskData, Handle hMutex);
    void WaitUntilTime(TaskData *taskData, Handle hMutex, Handle hTime);
    bool WakeThread(PolyObject *targetThread);

    // Generally, the system runs with multiple threads.  After a
    // fork, though, there is only one thread.
    bool singleThreaded;

    // Each thread has an entry in this array.
    TaskData **taskArray;
    unsigned taskArraySize; // Current size of the array.

    /* schedLock: This lock must be held when making scheduling decisions.
       It must also be held before adding items to taskArray, removing
       them or scanning the array.
       It must also be held before deleting a TaskData object
       or using it in a thread other than the "owner"  */
    PLock schedLock;
#ifdef HAVE_PTHREAD
    pthread_key_t tlsId;
#elif defined(HAVE_WINDOWS_H)
    DWORD tlsId;
#endif

    // We make an exception packet for Interrupt and store it here.
    // This exception can be raised if we run out of store so we need to
    // make sure we have the packet before we do.
    poly_exn *interrupt_exn;

    /* initialThreadWait: The initial thread waits on this for
       wake-ups from the ML threads requesting actions such as GC or
       close-down. */
    PCondVar initialThreadWait;
    // A requesting thread sets this to indicate the request.  This value
    // is only reset once the request has been satisfied.
    MainThreadRequest *threadRequest;

    PCondVar mlThreadWait;  // All the threads block on here until the request has completed.

    int exitResult;
    bool exitRequest;
    // Shutdown locking.
    void CrowBarFn(void);
    PLock shutdownLock;
    PCondVar crowbarLock;
    bool crowbarRunning;
#if (defined(HAVE_PTHREAD))
    pthread_t crowBarThreadId;
#elif defined(HAVE_WINDOWS_H)
    HANDLE hCrowBarThread;
#endif

#ifdef HAVE_WINDOWS_H
    // Used in profiling
    HANDLE hStopEvent; /* Signalled to stop all threads. */
    HANDLE profilingHd;
    HANDLE mainThreadHandle; // Handle for main thread
    LONGLONG lastCPUTime; // CPU used by main thread.
#endif

    TaskData *sigTask;  // Pointer to current signal task.
};

// Global process data.
static Processes processesModule;
ProcessExternal *processes = &processesModule;

Processes::Processes(): singleThreaded(false), taskArray(0), taskArraySize(0),
    schedLock("Scheduler"), interrupt_exn(0),
    threadRequest(0), exitResult(0), exitRequest(false),
    crowbarRunning(false), sigTask(0)
{
#if (defined(HAVE_PTHREAD))
#elif defined(HAVE_WINDOWS_H)
    hCrowBarThread = NULL;
#endif
#ifdef HAVE_WINDOWS_H
    Waiter::hWakeupEvent = NULL;
    hStopEvent = NULL;
    profilingHd = NULL;
    lastCPUTime = 0;
    mainThreadHandle = NULL;
#endif
}

enum _mainThreadPhase mainThreadPhase = MTP_USER_CODE;

// Get the attribute flags.
static POLYUNSIGNED ThreadAttrs(TaskData *taskData)
{
    return UNTAGGED_UNSIGNED(taskData->threadObject->flags);
}

// General interface to thread.  Ideally the various cases will be made into
// separate functions.
POLYUNSIGNED PolyThreadGeneral(PolyObject *threadId, PolyWord code, PolyWord arg)
{
    TaskData *taskData = TaskData::FindTaskForId(threadId);
    ASSERT(taskData != 0);
    taskData->PreRTSCall();
    Handle reset = taskData->saveVec.mark();
    Handle pushedCode = taskData->saveVec.push(code);
    Handle pushedArg = taskData->saveVec.push(arg);
    Handle result = 0;

    try {
        result = processesModule.ThreadDispatch(taskData, pushedArg, pushedCode);
    }
    catch (KillException &) {
        processes->ThreadExit(taskData); // TestSynchronousRequests may test for kill
    }
    catch (...) { } // If an ML exception is raised

    taskData->saveVec.reset(reset);
    taskData->PostRTSCall();
    if (result == 0) return TAGGED(0).AsUnsigned();
    else return result->Word().AsUnsigned();
}

POLYUNSIGNED PolyThreadMutexBlock(PolyObject *threadId, PolyWord arg)
{
    TaskData *taskData = TaskData::FindTaskForId(threadId);
    ASSERT(taskData != 0);
    taskData->PreRTSCall();
    Handle reset = taskData->saveVec.mark();
    Handle pushedArg = taskData->saveVec.push(arg);

    if (profileMode == kProfileMutexContention)
        taskData->addProfileCount(1);

    try {
        processesModule.MutexBlock(taskData, pushedArg);
    }
    catch (KillException &) {
        processes->ThreadExit(taskData); // TestSynchronousRequests may test for kill
    }
    catch (...) { } // If an ML exception is raised

    taskData->saveVec.reset(reset);
    taskData->PostRTSCall();
    return TAGGED(0).AsUnsigned();
}

POLYUNSIGNED PolyThreadMutexUnlock(PolyObject *threadId, PolyWord arg)
{
    TaskData *taskData = TaskData::FindTaskForId(threadId);
    ASSERT(taskData != 0);
    taskData->PreRTSCall();
    Handle reset = taskData->saveVec.mark();
    Handle pushedArg = taskData->saveVec.push(arg);

    try {
        processesModule.MutexUnlock(taskData, pushedArg);
    }
    catch (KillException &) {
        processes->ThreadExit(taskData); // TestSynchronousRequests may test for kill
    }
    catch (...) { } // If an ML exception is raised

    taskData->saveVec.reset(reset);
    taskData->PostRTSCall();
    return TAGGED(0).AsUnsigned();
}

/* A mutex was locked i.e. the count was ~1 or less.  We will have set it to
  ~1. This code blocks if the count is still ~1.  It does actually return
  if another thread tries to lock the mutex and hasn't yet set the value
  to ~1 but that doesn't matter since whenever we return we simply try to
  get the lock again. */
void Processes::MutexBlock(TaskData *taskData, Handle hMutex)
{
    schedLock.Lock();
    // We have to check the value again with schedLock held rather than
    // simply waiting because otherwise the unlocking thread could have
    // set the variable back to 1 (unlocked) and signalled any waiters
    // before we actually got to wait.  
    if (UNTAGGED(DEREFHANDLE(hMutex)->Get(0)) < 0)
    {
        // Set this so we can see what we're blocked on.
        taskData->blockMutex = DEREFHANDLE(hMutex);
        // Now release the ML memory.  A GC can start.
        ThreadReleaseMLMemoryWithSchedLock(taskData);
        // Wait until we're woken up.  We mustn't block if we have been
        // interrupted, and are processing interrupts asynchronously, or
        // we've been killed.
        switch (taskData->requests)
        {
        case kRequestKill:
            // We've been killed.  Handle this later.
            break;
        case kRequestInterrupt:
            {
                // We've been interrupted.  
                POLYUNSIGNED attrs = ThreadAttrs(taskData) & PFLAG_INTMASK;
                if (attrs == PFLAG_ASYNCH || attrs == PFLAG_ASYNCH_ONCE)
                    break;
                // If we're ignoring interrupts or handling them synchronously
                // we don't do anything here.
            }
        case kRequestNone:
            globalStats.incCount(PSC_THREADS_WAIT_MUTEX);
            taskData->threadLock.Wait(&schedLock);
            globalStats.decCount(PSC_THREADS_WAIT_MUTEX);
        }
        taskData->blockMutex = 0; // No longer blocked.
        ThreadUseMLMemoryWithSchedLock(taskData);
    }
    // Return and try and get the lock again.
    schedLock.Unlock();
    // Test to see if we have been interrupted and if this thread
    // processes interrupts asynchronously we should raise an exception
    // immediately.  Perhaps we do that whenever we exit from the RTS.
}

/* Unlock a mutex.  Called after incrementing the count and discovering
   that at least one other thread has tried to lock it.  We may need
   to wake up threads that are blocked. */
void Processes::MutexUnlock(TaskData *taskData, Handle hMutex)
{
    // The caller has already set the variable to 1 (unlocked).
    // We need to acquire schedLock so that we can
    // be sure that any thread that is trying to lock sees either
    // the updated value (and so doesn't wait) or has successfully
    // waited on its threadLock (and so will be woken up).
    schedLock.Lock();
    // Unlock any waiters.
    for (unsigned i = 0; i < taskArraySize; i++)
    {
        TaskData *p = taskArray[i];
        // If the thread is blocked on this mutex we can signal the thread.
        if (p && p->blockMutex == DEREFHANDLE(hMutex))
            p->threadLock.Signal();
    }
    schedLock.Unlock();
}

POLYUNSIGNED PolyThreadCondVarWait(PolyObject *threadId, PolyWord arg)
{
    TaskData *taskData = TaskData::FindTaskForId(threadId);
    ASSERT(taskData != 0);
    taskData->PreRTSCall();
    Handle reset = taskData->saveVec.mark();
    Handle pushedArg = taskData->saveVec.push(arg);

    try {
        processesModule.WaitInfinite(taskData, pushedArg);
    }
    catch (KillException &) {
        processes->ThreadExit(taskData); // TestSynchronousRequests may test for kill
    }
    catch (...) { } // If an ML exception is raised

    taskData->saveVec.reset(reset);
    taskData->PostRTSCall();
    return TAGGED(0).AsUnsigned();
}

POLYUNSIGNED PolyThreadCondVarWaitUntil(PolyObject *threadId, PolyWord lockArg, PolyWord timeArg)
{
    TaskData *taskData = TaskData::FindTaskForId(threadId);
    ASSERT(taskData != 0);
    taskData->PreRTSCall();
    Handle reset = taskData->saveVec.mark();
    Handle pushedLockArg = taskData->saveVec.push(lockArg);
    Handle pushedTimeArg = taskData->saveVec.push(timeArg);

    try {
        processesModule.WaitUntilTime(taskData, pushedLockArg, pushedTimeArg);
    }
    catch (KillException &) {
        processes->ThreadExit(taskData); // TestSynchronousRequests may test for kill
    }
    catch (...) { } // If an ML exception is raised

    taskData->saveVec.reset(reset);
    taskData->PostRTSCall();
    return TAGGED(0).AsUnsigned();
}

// Atomically drop a mutex and wait for a wake up.
// It WILL NOT RAISE AN EXCEPTION unless it is set to handle exceptions
// asynchronously (which it shouldn't do if the ML caller code is correct).
// It may return as a result of any of the following:
//      an explicit wake up.
//      an interrupt, either direct or broadcast
//      a trap i.e. a request to handle an asynchronous event.
void Processes::WaitInfinite(TaskData *taskData, Handle hMutex)
{
    schedLock.Lock();
    // Atomically release the mutex.  This is atomic because we hold schedLock
    // so no other thread can call signal or broadcast.
    Handle decrResult = taskData->AtomicIncrement(hMutex);
    if (UNTAGGED(decrResult->Word()) != 1)
    {
        taskData->AtomicReset(hMutex);
        // The mutex was locked so we have to release any waiters.
        // Unlock any waiters.
        for (unsigned i = 0; i < taskArraySize; i++)
        {
            TaskData *p = taskArray[i];
            // If the thread is blocked on this mutex we can signal the thread.
            if (p && p->blockMutex == DEREFHANDLE(hMutex))
                p->threadLock.Signal();
        }
    }
    // Wait until we're woken up.  Don't block if we have been interrupted
    // or killed.
    if (taskData->requests == kRequestNone)
    {
        // Now release the ML memory.  A GC can start.
        ThreadReleaseMLMemoryWithSchedLock(taskData);
        globalStats.incCount(PSC_THREADS_WAIT_CONDVAR);
        taskData->threadLock.Wait(&schedLock);
        globalStats.decCount(PSC_THREADS_WAIT_CONDVAR);
        // We want to use the memory again.
        ThreadUseMLMemoryWithSchedLock(taskData);
    }
    schedLock.Unlock();
}

// Atomically drop a mutex and wait for a wake up or a time to wake up
void Processes::WaitUntilTime(TaskData *taskData, Handle hMutex, Handle hWakeTime)
{
    // Convert the time into the correct format for WaitUntil before acquiring
    // schedLock.  div_longc could do a GC which requires schedLock.
#if (defined(_WIN32) && ! defined(__CYGWIN__))
    // On Windows it is the number of 100ns units since the epoch
    FILETIME tWake;
    getFileTimeFromArb(taskData, hWakeTime, &tWake);
#else
    // Unix style times.
    struct timespec tWake;
    // On Unix we represent times as a number of microseconds.
    Handle hMillion = Make_arbitrary_precision(taskData, 1000000);
    tWake.tv_sec =
        get_C_ulong(taskData, DEREFWORDHANDLE(div_longc(taskData, hMillion, hWakeTime)));
    tWake.tv_nsec =
        1000*get_C_ulong(taskData, DEREFWORDHANDLE(rem_longc(taskData, hMillion, hWakeTime)));
#endif
    schedLock.Lock();
    // Atomically release the mutex.  This is atomic because we hold schedLock
    // so no other thread can call signal or broadcast.
    Handle decrResult = taskData->AtomicIncrement(hMutex);
    if (UNTAGGED(decrResult->Word()) != 1)
    {
        taskData->AtomicReset(hMutex);
        // The mutex was locked so we have to release any waiters.
        // Unlock any waiters.
        for (unsigned i = 0; i < taskArraySize; i++)
        {
            TaskData *p = taskArray[i];
            // If the thread is blocked on this mutex we can signal the thread.
            if (p && p->blockMutex == DEREFHANDLE(hMutex))
                p->threadLock.Signal();
        }
    }
    // Wait until we're woken up.  Don't block if we have been interrupted
    // or killed.
    if (taskData->requests == kRequestNone)
    {
        // Now release the ML memory.  A GC can start.
        ThreadReleaseMLMemoryWithSchedLock(taskData);
        globalStats.incCount(PSC_THREADS_WAIT_CONDVAR);
        (void)taskData->threadLock.WaitUntil(&schedLock, &tWake);
        globalStats.decCount(PSC_THREADS_WAIT_CONDVAR);
        // We want to use the memory again.
        ThreadUseMLMemoryWithSchedLock(taskData);
    }
    schedLock.Unlock();
}

bool Processes::WakeThread(PolyObject *targetThread)
{
    bool result = false; // Default to failed.
    // Acquire the schedLock first.  This ensures that this is
    // atomic with respect to waiting.
    schedLock.Lock();
    TaskData *p = TaskForIdentifier(targetThread);
    if (p && p->threadObject == targetThread)
    {
        POLYUNSIGNED attrs = ThreadAttrs(p) & PFLAG_INTMASK;
        if (p->requests == kRequestNone ||
            (p->requests == kRequestInterrupt && attrs == PFLAG_IGNORE))
        {
            p->threadLock.Signal();
            result = true;
        }
    }
    schedLock.Unlock();
    return result;
}

POLYUNSIGNED PolyThreadCondVarWake(PolyWord targetThread)
{
    if (processesModule.WakeThread(targetThread.AsObjPtr()))
        return TAGGED(1).AsUnsigned();
    else return TAGGED(0).AsUnsigned();
}

// Test if a thread is active.
POLYUNSIGNED PolyThreadIsActive(PolyWord targetThread)
{
    processesModule.schedLock.Lock();
    TaskData *p = processesModule.TaskForIdentifier(targetThread.AsObjPtr());
    processesModule.schedLock.Unlock();
    if (p != 0) return TAGGED(1).AsUnsigned();
    else return TAGGED(0).AsUnsigned();
}

// Send an interrupt to a specific thread
POLYUNSIGNED PolyThreadInterruptThread(PolyWord targetThread)
{
    processesModule.schedLock.Lock();
    TaskData *p = processesModule.TaskForIdentifier(targetThread.AsObjPtr());
    if (p) processesModule.MakeRequest(p, kRequestInterrupt);
    processesModule.schedLock.Unlock();
    // If the thread cannot be identified return false.
    // The caller can then raise an exception
    if (p == 0) return TAGGED(0).AsUnsigned();
    else return TAGGED(1).AsUnsigned();
}

// Kill a specific thread
POLYUNSIGNED PolyThreadKillThread(PolyWord targetThread)
{
    processesModule.schedLock.Lock();
    TaskData *p = processesModule.TaskForIdentifier(targetThread.AsObjPtr());
    if (p) processesModule.MakeRequest(p, kRequestKill);
    processesModule.schedLock.Unlock();
    // If the thread cannot be identified return false.
    // The caller can then raise an exception
    if (p == 0) return TAGGED(0).AsUnsigned();
    else return TAGGED(1).AsUnsigned();
}

POLYUNSIGNED PolyThreadBroadcastInterrupt(void)
{
    processesModule.BroadcastInterrupt();
    return TAGGED(0).AsUnsigned();
}

POLYUNSIGNED PolyThreadTestInterrupt(PolyWord threadId)
{
    TaskData *taskData = TaskData::FindTaskForId(threadId.AsObjPtr());
    ASSERT(taskData != 0);
    taskData->PreRTSCall();
    Handle reset = taskData->saveVec.mark();

    try {
        processesModule.TestSynchronousRequests(taskData);
        // Also process any asynchronous requests that may be pending.
        // These will be handled "soon" but if we have just switched from deferring
        // interrupts this guarantees that any deferred interrupts will be handled now.
        if (processesModule.ProcessAsynchRequests(taskData))
            throw IOException();
    }
    catch (KillException &) {
        processes->ThreadExit(taskData); // TestSynchronousRequests may test for kill
    }
    catch (...) { } // If an ML exception is raised

    taskData->saveVec.reset(reset);
    taskData->PostRTSCall();
    return TAGGED(0).AsUnsigned();
}

// Return the number of processors.
// Returns 1 if there is any problem.
POLYUNSIGNED PolyThreadNumProcessors(void)
{
    return TAGGED(NumberOfProcessors()).AsUnsigned();
}

// Return the number of physical processors.
// Returns 0 if there is any problem.
POLYUNSIGNED PolyThreadNumPhysicalProcessors(void)
{
    return TAGGED(NumberOfPhysicalProcessors()).AsUnsigned();
}

// Set the maximum stack size.
POLYUNSIGNED PolyThreadMaxStackSize(PolyObject *threadId, PolyWord newSize)
{
    TaskData *taskData = TaskData::FindTaskForId(threadId);
    ASSERT(taskData != 0);
    taskData->PreRTSCall();
    Handle reset = taskData->saveVec.mark();

    try {
            taskData->threadObject->mlStackSize = newSize;
            if (newSize != TAGGED(0))
            {
                POLYUNSIGNED current = taskData->currentStackSpace(); // Current size in words
                POLYUNSIGNED newWords = getPolyUnsigned(taskData, newSize);
                if (current > newWords)
                    raise_exception0(taskData, EXC_interrupt);
            }
    }
    catch (KillException &) {
        processes->ThreadExit(taskData); // TestSynchronousRequests may test for kill
    }
    catch (...) { } // If an ML exception is raised

    taskData->saveVec.reset(reset);
    taskData->PostRTSCall();
    return TAGGED(0).AsUnsigned();
}

// Old dispatch function.  This is only required because the pre-built compiler
// may use some of these e.g. fork.
Handle Processes::ThreadDispatch(TaskData *taskData, Handle args, Handle code)
{
    unsigned c = get_C_unsigned(taskData, DEREFWORDHANDLE(code));
    TaskData *ptaskData = taskData;
    switch (c)
    {
    case 1:
        MutexBlock(taskData, args);
        return SAVE(TAGGED(0));

    case 2:
        MutexUnlock(taskData, args);
        return SAVE(TAGGED(0));

    case 7: // Fork a new thread.  The arguments are the function to run and the attributes.
            return ForkThread(ptaskData, SAVE(args->WordP()->Get(0)),
                        (Handle)0, args->WordP()->Get(1),
                        // For backwards compatibility we check the length here
                        args->WordP()->Length() <= 2 ? TAGGED(0) : args->WordP()->Get(2));

    case 10: // Broadcast an interrupt to all threads that are interested.
        BroadcastInterrupt();
        return SAVE(TAGGED(0));

    default:
        {
            char msg[100];
            sprintf(msg, "Unknown thread function: %u", c);
            raise_fail(taskData, msg);
            return 0;
        }
    }
}

// Fill unused allocation space with a dummy object to preserve the invariant
// that memory is always valid.
void TaskData::FillUnusedSpace(void)
{
    if (allocPointer > allocLimit)
        gMem.FillUnusedSpace(allocLimit, allocPointer-allocLimit); 
}


TaskData::TaskData(): allocPointer(0), allocLimit(0), allocSize(MIN_HEAP_SIZE), allocCount(0),
        stack(0), threadObject(0), signalStack(0), foreignStack(TAGGED(0)),
        inML(false), requests(kRequestNone), blockMutex(0), inMLHeap(false),
        runningProfileTimer(false)
{
#ifdef HAVE_WINDOWS_H
    lastCPUTime = 0;
#endif
#ifdef HAVE_WINDOWS_H
    threadHandle = 0;
#endif
    threadExited = false;
}

TaskData::~TaskData()
{
    if (signalStack) free(signalStack);
    if (stack) gMem.DeleteStackSpace(stack);
#ifdef HAVE_WINDOWS_H
    if (threadHandle) CloseHandle(threadHandle);
#endif
}


// Find a task that matches the specified identifier and returns
// it if it exists.  MUST be called with schedLock held.
TaskData *Processes::TaskForIdentifier(PolyObject *taskId)
{
    // The index is in the first word of the thread object.
    unsigned index = (unsigned)(UNTAGGED_UNSIGNED(taskId->Get(0)));
    // Check the index is valid and matches the object stored in the table.
    if (index < taskArraySize)
    {
        TaskData *p = taskArray[index];
        if (p && p->threadObject == taskId)
            return p;
    }
    return 0;
}

// Return the task data for a task id.
TaskData *TaskData::FindTaskForId(PolyObject *taskId)
{
    PLocker lock(&processesModule.schedLock);
    return processesModule.TaskForIdentifier(taskId);
}

// Broadcast an interrupt to all relevant threads.
void Processes::BroadcastInterrupt(void)
{
    // If a thread is set to accept broadcast interrupts set it to
    // "interrupted".
    schedLock.Lock();
    for (unsigned i = 0; i < taskArraySize; i++)
    {
        TaskData *p = taskArray[i];
        if (p)
        {
            POLYUNSIGNED attrs = ThreadAttrs(p);
            if (attrs & PFLAG_BROADCAST)
                MakeRequest(p, kRequestInterrupt);
        }
    }
    schedLock.Unlock();
}

// Set the asynchronous request variable for the thread.  Must be called
// with the schedLock held.  Tries to wake the thread up if possible.
void Processes::MakeRequest(TaskData *p, ThreadRequests request)
{
    // We don't override a request to kill by an interrupt request.
    if (p->requests < request)
    {
        p->requests = request;
        p->InterruptCode();
        p->threadLock.Signal();
        // Set the value in the ML object as well so the ML code can see it
        p->threadObject->requestCopy = TAGGED(request);
    }
#ifdef HAVE_WINDOWS_H
    // Wake any threads waiting for IO
    PulseEvent(Waiter::hWakeupEvent);
#endif
}

void Processes::ThreadExit(TaskData *taskData)
{
    if (debugOptions & DEBUG_THREADS)
        Log("THREAD: Thread %p exiting\n", taskData);

#ifdef HAVE_PTHREAD
    // Block any profile interrupt from now on.  We're deleting the ML stack for this thread.
    sigset_t block_sigs;
    sigemptyset(&block_sigs);
    sigaddset(&block_sigs, SIGVTALRM);
    pthread_sigmask(SIG_BLOCK, &block_sigs, NULL);
    // Remove the thread-specific data since it's no
    // longer valid.
    pthread_setspecific(tlsId, 0);
#endif

    globalStats.decCount(PSC_THREADS);

    if (singleThreaded) finish(0);

    schedLock.Lock();
    ThreadReleaseMLMemoryWithSchedLock(taskData); // Allow a GC if it was waiting for us.
    taskData->threadExited = true;
    initialThreadWait.Signal(); // Tell it we've finished.
    schedLock.Unlock();
#ifdef HAVE_PTHREAD
    pthread_exit(0);
#elif defined(HAVE_WINDOWS_H)
    ExitThread(0);
#endif
}

// These two functions are used for calls from outside where
// the lock has not yet been acquired.
void Processes::ThreadUseMLMemory(TaskData *taskData)
{
    // Trying to acquire the lock here may block if a GC is in progress
    schedLock.Lock();
    ThreadUseMLMemoryWithSchedLock(taskData);
    schedLock.Unlock();
}

void Processes::ThreadReleaseMLMemory(TaskData *taskData)
{
    schedLock.Lock();
    ThreadReleaseMLMemoryWithSchedLock(taskData);
    schedLock.Unlock();
}

// Called when a thread wants to resume using the ML heap.  That could
// be after a wait for some reason or after executing some foreign code.
// Since there could be a GC in progress already at this point we may either
// be blocked waiting to acquire schedLock or we may need to wait until
// we are woken up at the end of the GC.
void Processes::ThreadUseMLMemoryWithSchedLock(TaskData *taskData)
{
    TaskData *ptaskData = taskData;
    // If there is a request outstanding we have to wait for it to
    // complete.  We notify the root thread and wait for it.
    while (threadRequest != 0)
    {
        initialThreadWait.Signal();
        // Wait for the GC to happen
        mlThreadWait.Wait(&schedLock);
    }
    ASSERT(! ptaskData->inMLHeap);
    ptaskData->inMLHeap = true;
}

// Called to indicate that the thread has temporarily finished with the
// ML memory either because it is going to wait for something or because
// it is going to run foreign code.  If there is an outstanding GC request
// that can proceed.
void Processes::ThreadReleaseMLMemoryWithSchedLock(TaskData *taskData)
{
    TaskData *ptaskData = taskData;
    ASSERT(ptaskData->inMLHeap);
    ptaskData->inMLHeap = false;
    // Put a dummy object in any unused space.  This maintains the
    // invariant that the allocated area is filled with valid objects.
    ptaskData->FillUnusedSpace();
    //
    if (threadRequest != 0)
        initialThreadWait.Signal();
}


// Make a request to the root thread.
void Processes::MakeRootRequest(TaskData *taskData, MainThreadRequest *request)
{
    if (singleThreaded)
    {
        mainThreadPhase = request->mtp;
        ThreadReleaseMLMemoryWithSchedLock(taskData); // Primarily to call FillUnusedSpace
        request->Perform();
        ThreadUseMLMemoryWithSchedLock(taskData);
        mainThreadPhase = MTP_USER_CODE;
    }
    else
    {
        PLocker locker(&schedLock);

        // Wait for any other requests. 
        while (threadRequest != 0)
        {
            // Deal with any pending requests.
            ThreadReleaseMLMemoryWithSchedLock(taskData);
            ThreadUseMLMemoryWithSchedLock(taskData); // Drops schedLock while waiting.
        }
        // Now the other requests have been dealt with (and we have schedLock).
        request->completed = false;
        threadRequest = request;
        // Wait for it to complete.
        while (! request->completed)
        {
            ThreadReleaseMLMemoryWithSchedLock(taskData);
            ThreadUseMLMemoryWithSchedLock(taskData); // Drops schedLock while waiting.
        }
    }
}

// Find space for an object.  Returns a pointer to the start.  "words" must include
// the length word and the result points at where the length word will go.
PolyWord *Processes::FindAllocationSpace(TaskData *taskData, POLYUNSIGNED words, bool alwaysInSeg)
{
    bool triedInterrupt = false;

    while (1)
    {
        // After a GC allocPointer and allocLimit are zero and when allocating the
        // heap segment we request a minimum of zero words.
        if (taskData->allocPointer != 0 && taskData->allocPointer >= taskData->allocLimit + words)
        {
            // There's space in the current segment,
            taskData->allocPointer -= words;
            return taskData->allocPointer;
        }
        else // Insufficient space in this area. 
        {
            if (words > taskData->allocSize && ! alwaysInSeg)
            {
                // If the object we want is larger than the heap segment size
                // we allocate it separately rather than in the segment.
                PolyWord *foundSpace = gMem.AllocHeapSpace(words);
                if (foundSpace) return foundSpace;
            }
            else
            {
                // Fill in any unused space in the existing segment
                taskData->FillUnusedSpace();
                // Get another heap segment with enough space for this object.
                POLYUNSIGNED requestSpace = taskData->allocSize+words;
                POLYUNSIGNED spaceSize = requestSpace;
                // Get the space and update spaceSize with the actual size.
                PolyWord *space = gMem.AllocHeapSpace(words, spaceSize);
                if (space)
                {
                    // Double the allocation size for the next time if
                    // we succeeded in allocating the whole space.
                    taskData->allocCount++; 
                    if (spaceSize == requestSpace) taskData->allocSize = taskData->allocSize*2;
                    taskData->allocLimit = space;
                    taskData->allocPointer = space+spaceSize;
                    // Actually allocate the object
                    taskData->allocPointer -= words;
                    return taskData->allocPointer;
                }
            }

            // It's possible that another thread has requested a GC in which case
            // we will have memory when that happens.  We don't want to start
            // another GC.
            if (! singleThreaded)
            {
                PLocker locker(&schedLock);
                if (threadRequest != 0)
                {
                    ThreadReleaseMLMemoryWithSchedLock(taskData);
                    ThreadUseMLMemoryWithSchedLock(taskData);
                    continue; // Try again
                }
            }

            // Try garbage-collecting.  If this failed return 0.
            if (! QuickGC(taskData, words))
            {
                extern FILE *polyStderr;
                if (! triedInterrupt)
                {
                    triedInterrupt = true;
                    fprintf(polyStderr,"Run out of store - interrupting threads\n");
                    if (debugOptions & DEBUG_THREADS)
                        Log("THREAD: Run out of store, interrupting threads\n");
                    BroadcastInterrupt();
                    try {
                        if (ProcessAsynchRequests(taskData))
                            return 0; // Has been interrupted.
                    }
                    catch(KillException &)
                    {
                        // The thread may have been killed.
                        processes->ThreadExit(taskData);
                    }
                    // Not interrupted: pause this thread to allow for other
                    // interrupted threads to free something.
#if defined(_WIN32)
                    Sleep(5000);
#else
                    sleep(5);
#endif
                    // Try again.
                }
                else {
                    // That didn't work.  Exit.
                    fprintf(polyStderr,"Failed to recover - exiting\n");
                    Exit(1); // Begins the shutdown process
                    processes->ThreadExit(taskData); // And terminate this thread.
                }
             }
            // Try again.  There should be space now.
        }
    }
}

#ifdef _MSC_VER
// Don't tell me that exitThread has a non-void type.
#pragma warning(disable:4646)
#endif

Handle exitThread(TaskData *taskData)
/* A call to this is put on the stack of a new thread so when the
   thread function returns the thread goes away. */  
{
    processesModule.ThreadExit(taskData);
}

// Terminate the current thread.  Never returns.
POLYUNSIGNED PolyThreadKillSelf(PolyObject *threadId)
{
    TaskData *taskData = TaskData::FindTaskForId(threadId);
    ASSERT(taskData != 0);
    taskData->PreRTSCall(); // Possibly not needed since we never return
    processesModule.ThreadExit(taskData);
    return 0; 
}

/* Called when a thread is about to block, usually because of IO.
   If this is interruptable (currently only used for Posix functions)
   the process will be set to raise an exception if any signal is handled.
   It may also raise an exception if another thread has called
   broadcastInterrupt. */
void Processes::ThreadPauseForIO(TaskData *taskData, Waiter *pWait)
{
    TestAnyEvents(taskData); // Consider this a blocking call that may raise Interrupt
    ThreadReleaseMLMemory(taskData);
    globalStats.incCount(PSC_THREADS_WAIT_IO);
    pWait->Wait(1000); // Wait up to a second
    globalStats.decCount(PSC_THREADS_WAIT_IO);
    ThreadUseMLMemory(taskData);
    TestAnyEvents(taskData); // Check if we've been interrupted.
}

// Default waiter: simply wait for the time.  In the case of Windows it
// is also woken up if the event is signalled.  In Unix it may be woken
// up by a signal.
void Waiter::Wait(unsigned maxMillisecs)
{
    // Since this is used only when we can't monitor the source directly
    // we set this to 10ms so that we're not waiting too long.
    if (maxMillisecs > 10) maxMillisecs = 10;
#if (defined(_WIN32) && ! defined(__CYGWIN__))
    /* We seem to need to reset the queue before calling
       MsgWaitForMultipleObjects otherwise it frequently returns
       immediately, often saying there is a message with a message ID
       of 0x118 which doesn't correspond to any listed message.
       While calling PeekMessage afterwards might be better this doesn't
       seem to work properly.  We need to use MsgWaitForMultipleObjects
       here so that we get a reasonable response with the Windows GUI. */
    MSG msg;
    // N.B.  It seems that calling PeekMessage may result in a callback
    // to a window proc directly without a call to DispatchMessage.  That
    // could result in a recursive call here if we have installed an ML
    // window proc.
    PeekMessage(&msg, 0, 0, 0, PM_NOREMOVE);
    // Wait until we get input or we're woken up.
    MsgWaitForMultipleObjects(1, &hWakeupEvent, FALSE, maxMillisecs, QS_ALLINPUT);
#else
    // Unix
    fd_set read_fds, write_fds, except_fds;
    struct timeval toWait = { 0, 0 };
    toWait.tv_sec = maxMillisecs / 1000;
    toWait.tv_usec = (maxMillisecs % 1000) * 1000;
    FD_ZERO(&read_fds);
    FD_ZERO(&write_fds);
    FD_ZERO(&except_fds);
    select(FD_SETSIZE, &read_fds, &write_fds, &except_fds, &toWait);
#endif
}

static Waiter defWait;
Waiter *Waiter::defaultWaiter = &defWait;

#ifdef HAVE_WINDOWS_H
// Windows and Cygwin
HANDLE Waiter::hWakeupEvent; // Pulsed to wake up any threads waiting for IO.

// Wait for the specified handle to be signalled.
void WaitHandle::Wait(unsigned maxMillisecs)
{
    MSG msg;
    PeekMessage(&msg, 0, 0, 0, PM_NOREMOVE);

    HANDLE hEvents[2];
    DWORD dwEvents = 0;
    hEvents[dwEvents++] = Waiter::hWakeupEvent;
    if (m_Handle != NULL)
        hEvents[dwEvents++] = m_Handle;
    // Wait until we get input or we're woken up.
    MsgWaitForMultipleObjects(dwEvents, hEvents, FALSE, maxMillisecs, QS_ALLINPUT);
}
#endif

#if (!defined(_WIN32) || defined(__CYGWIN__))
// Unix and Cygwin: Wait for a file descriptor on input.
void WaitInputFD::Wait(unsigned maxMillisecs)
{
    fd_set read_fds, write_fds, except_fds;
    struct timeval toWait = { 0, 0 };
    toWait.tv_sec = maxMillisecs / 1000;
    toWait.tv_usec = (maxMillisecs % 1000) * 1000;
    FD_ZERO(&read_fds);
    if (m_waitFD >= 0) FD_SET(m_waitFD, &read_fds);
    FD_ZERO(&write_fds);
    FD_ZERO(&except_fds);
    select(FD_SETSIZE, &read_fds, &write_fds, &except_fds, &toWait);
}
#endif

// Get the task data for the current thread.  This is held in
// thread-local storage.  Normally this is passed in taskData but
// in a few cases this isn't available.
TaskData *Processes::GetTaskDataForThread(void)
{
#ifdef HAVE_PTHREAD
    return (TaskData *)pthread_getspecific(tlsId);
#elif defined(HAVE_WINDOWS_H)
    return (TaskData *)TlsGetValue(tlsId);
#else
    // If there's no threading.
    return taskArray[0];
#endif
}

// Called to create a task data object in the current thread.
// This is currently only used if a thread created in foreign code calls
// a callback.
TaskData *Processes::CreateNewTaskData(Handle threadId, Handle threadFunction,
                           Handle args, PolyWord flags)
{
    TaskData *taskData = machineDependent->CreateTaskData();
#if defined(HAVE_WINDOWS_H)
    HANDLE thisProcess = GetCurrentProcess();
    DuplicateHandle(thisProcess, GetCurrentThread(), thisProcess, 
        &(taskData->threadHandle), THREAD_ALL_ACCESS, FALSE, 0);
#endif
    unsigned thrdIndex;

    {
        PLocker lock(&schedLock);
        // See if there's a spare entry in the array.
        for (thrdIndex = 0;
                thrdIndex < taskArraySize && taskArray[thrdIndex] != 0;
                thrdIndex++);

        if (thrdIndex == taskArraySize) // Need to expand the array
        {
            TaskData **newArray =
                (TaskData **)realloc(taskArray, sizeof(TaskData *)*(taskArraySize+1));
            if (newArray)
            {
                taskArray = newArray;
                taskArraySize++;
            }
            else
            {
                delete(taskData);
                schedLock.Unlock();
                throw MemoryException();
            }
        }
        // Add into the new entry
        taskArray[thrdIndex] = taskData;
    }

    taskData->stack = gMem.NewStackSpace(machineDependent->InitialStackSize());
    if (taskData->stack == 0)
    {
        delete(taskData);
        throw MemoryException();
    }

    // TODO:  Check that there isn't a problem if we try to allocate
    // memory here and result in a GC.
    taskData->InitStackFrame(taskData, threadFunction, args);

    ThreadUseMLMemory(taskData);

    // If the forking thread has created an ML thread object use that
    // otherwise create a new one in the current context.
    if (threadId != 0)
        taskData->threadObject = (ThreadObject*)threadId->WordP();
    else
    {
        taskData->threadObject = (ThreadObject*)alloc(taskData, sizeof(ThreadObject)/sizeof(PolyWord), F_MUTABLE_BIT);
        taskData->threadObject->index = TAGGED(thrdIndex); // Set to the index
        taskData->threadObject->flags = flags != TAGGED(0) ? TAGGED(PFLAG_SYNCH): flags;
        taskData->threadObject->threadLocal = TAGGED(0); // Empty thread-local store
        taskData->threadObject->requestCopy = TAGGED(0); // Cleared interrupt state
        taskData->threadObject->mlStackSize = TAGGED(0); // Unlimited stack size
        for (unsigned i = 0; i < sizeof(taskData->threadObject->debuggerSlots)/sizeof(PolyWord); i++)
            taskData->threadObject->debuggerSlots[i] = TAGGED(0);
    }

#ifdef HAVE_PTHREAD
    initThreadSignals(taskData);
    pthread_setspecific(tlsId, taskData);
#elif defined(HAVE_WINDOWS_H)
    TlsSetValue(tlsId, taskData);
#endif
    globalStats.incCount(PSC_THREADS);

    return taskData;
}

// This function is run when a new thread has been forked.  The
// parameter is the taskData value for the new thread.  This function
// is also called directly for the main thread.
#ifdef HAVE_PTHREAD
static void *NewThreadFunction(void *parameter)
{
    TaskData *taskData = (TaskData *)parameter;
#ifdef HAVE_WINDOWS_H
    // Cygwin: Get the Windows thread handle in case it's needed for profiling.
    HANDLE thisProcess = GetCurrentProcess();
    DuplicateHandle(thisProcess, GetCurrentThread(), thisProcess, 
        &(taskData->threadHandle), THREAD_ALL_ACCESS, FALSE, 0);
#endif
    initThreadSignals(taskData);
    pthread_setspecific(processesModule.tlsId, taskData);
    taskData->saveVec.init(); // Remove initial data
    globalStats.incCount(PSC_THREADS);
    processes->ThreadUseMLMemory(taskData);
    try {
        (void)taskData->EnterPolyCode(); // Will normally (always?) call ExitThread.
    }
    catch (KillException &) {
        processesModule.ThreadExit(taskData);
    }

    return 0;
}
#elif defined(HAVE_WINDOWS_H)
static DWORD WINAPI NewThreadFunction(void *parameter)
{
    TaskData *taskData = (TaskData *)parameter;
    TlsSetValue(processesModule.tlsId, taskData);
    taskData->saveVec.init(); // Removal initial data
    globalStats.incCount(PSC_THREADS);
    processes->ThreadUseMLMemory(taskData);
    try {
        (void)taskData->EnterPolyCode();
    }
    catch (KillException &) {
        processesModule.ThreadExit(taskData);
    }
    return 0;
}
#else
static void NewThreadFunction(void *parameter)
{
    TaskData *taskData = (TaskData *)parameter;
    initThreadSignals(taskData);
    taskData->saveVec.init(); // Removal initial data
    globalStats.incCount(PSC_THREADS);
    processes->ThreadUseMLMemory(taskData);
    try {
        (void)taskData->EnterPolyCode();
    }
    catch (KillException &) {
        processesModule.ThreadExit(taskData);
    }
}
#endif

// Sets up the initial thread from the root function.  This is run on
// the initial thread of the process so it will work if we don't
// have pthreads.
// When multithreading this thread also deals with all garbage-collection
// and similar operations and the ML threads send it requests to deal with
// that.  These require all the threads to pause until the operation is complete
// since they affect all memory but they are also sometimes highly recursive.
// On Mac OS X and on Linux if the stack limit is set to unlimited only the
// initial thread has a large stack and newly created threads have smaller
// stacks.  We need to make sure that any significant stack usage occurs only
// on the inital thread.
void Processes::BeginRootThread(PolyObject *rootFunction)
{
    if (taskArraySize < 1)
    {
        taskArray = (TaskData **)realloc(taskArray, sizeof(TaskData *));
        if (taskArray == 0) ::Exit("Unable to create the initial thread - insufficient memory");
        taskArraySize = 1;
    }

    try {
        // We can't use ForkThread because we don't have a taskData object before we start
        TaskData *taskData = machineDependent->CreateTaskData();
        taskData->threadObject = (ThreadObject*)alloc(taskData, sizeof(ThreadObject) / sizeof(PolyWord), F_MUTABLE_BIT);
        taskData->threadObject->index = TAGGED(0); // Index 0
        // The initial thread is set to accept broadcast interrupt requests
        // and handle them synchronously.  This is for backwards compatibility.
        taskData->threadObject->flags = TAGGED(PFLAG_BROADCAST|PFLAG_ASYNCH); // Flags
        taskData->threadObject->threadLocal = TAGGED(0); // Empty thread-local store
        taskData->threadObject->requestCopy = TAGGED(0); // Cleared interrupt state
        taskData->threadObject->mlStackSize = TAGGED(0); // Unlimited stack size
        for (unsigned i = 0; i < sizeof(taskData->threadObject->debuggerSlots)/sizeof(PolyWord); i++)
            taskData->threadObject->debuggerSlots[i] = TAGGED(0);
#if defined(HAVE_WINDOWS_H)
        taskData->threadHandle = mainThreadHandle;
#endif
        taskArray[0] = taskData;

        taskData->stack = gMem.NewStackSpace(machineDependent->InitialStackSize());
        if (taskData->stack == 0)
            ::Exit("Unable to create the initial thread - insufficient memory");

        taskData->InitStackFrame(taskData, taskData->saveVec.push(rootFunction), (Handle)0);

        // Create a packet for the Interrupt exception once so that we don't have to
        // allocate when we need to raise it.
        // We can only do this once the taskData object has been created.
        if (interrupt_exn == 0)
            interrupt_exn = makeExceptionPacket(taskData, EXC_interrupt);

        if (singleThreaded)
        {
            // If we don't have threading enter the code as if this were a new thread.
            // This will call finish so will never return.
            NewThreadFunction(taskData);
        }

        schedLock.Lock();
        int errorCode = 0;
#ifdef HAVE_PTHREAD
        if (pthread_create(&taskData->threadId, NULL, NewThreadFunction, taskData) != 0)
            errorCode = errno;
#elif defined(HAVE_WINDOWS_H)
        taskData->threadHandle =
            CreateThread(NULL, 0, NewThreadFunction, taskData, 0, NULL);
        if (taskData->threadHandle == NULL) errorCode = GetLastError();
#endif
        if (errorCode != 0)
        {
            // Thread creation failed.
            taskArray[0] = 0;
            delete(taskData);
            ExitWithError("Unable to create initial thread:", errorCode);
        }

        if (debugOptions & DEBUG_THREADS)
            Log("THREAD: Forked initial root thread %p\n", taskData);
    }
    catch (std::bad_alloc &) {
        ::Exit("Unable to create the initial thread - insufficient memory");
    }

    // Wait until the threads terminate or make a request.
    // We only release schedLock while waiting.
    while (1)
    {
        // Look at the threads to see if they are running.
        bool allStopped = true;
        bool noUserThreads = true;
        bool signalThreadRunning = false;
        for (unsigned i = 0; i < taskArraySize; i++)
        {
            TaskData *p = taskArray[i];
            if (p)
            {
                if (p == sigTask) signalThreadRunning = true;
                else noUserThreads = false;

                if (p->inMLHeap)
                {
                    allStopped = false;
                    // It must be running - interrupt it if we are waiting.
                    if (threadRequest != 0) p->InterruptCode();
                }
                else if (p->threadExited) // Has the thread terminated?
                {
                    // Wait for it to actually stop then delete the task data.
#ifdef HAVE_PTHREAD
                    pthread_join(p->threadId, NULL);
#elif defined(HAVE_WINDOWS_H)
                    WaitForSingleObject(p->threadHandle, INFINITE);
#endif
                    delete(p);
                    taskArray[i] = 0;
                    globalStats.decCount(PSC_THREADS);
                }
            }
        }
        if (noUserThreads)
        {
            // If all threads apart from the signal thread have exited then
            // we can finish but we must make sure that the signal thread has
            // exited before we finally finish and deallocate the memory.
            if (signalThreadRunning) exitRequest = true;
            else break; // Really no threads.
        }

        if (allStopped && threadRequest != 0)
        {
            mainThreadPhase = threadRequest->mtp;
            gMem.ProtectImmutable(false); // GC, sharing and export may all write to the immutable area
            threadRequest->Perform();
            gMem.ProtectImmutable(true);
            mainThreadPhase = MTP_USER_CODE;
            threadRequest->completed = true;
            threadRequest = 0; // Allow a new request.
            mlThreadWait.Signal();
        }

        // Have we had a request to stop?  This may have happened while in the GC.
        if (exitRequest)
        {
            // Set this to kill the threads.
            for (unsigned i = 0; i < taskArraySize; i++)
            {
                TaskData *taskData = taskArray[i];
                if (taskData && taskData->requests != kRequestKill)
                    MakeRequest(taskData, kRequestKill);
            }
            // Leave exitRequest set so that if we're in the process of
            // creating a new thread we will request it to stop when the
            // taskData object has been added to the table.
        }

        // Now release schedLock and wait for a thread
        // to wake us up.  Use a timed wait to avoid the race with
        // setting exitRequest.
        initialThreadWait.WaitFor(&schedLock, 400);
        // Update the periodic stats.
        // Calculate the free memory.  We have to be careful here because although
        // we have the schedLock we don't have any lock that prevents a thread
        // from allocating a new segment.  Since these statistics are only
        // very rough it doesn't matter if there's a glitch.
        // One possibility would be see if the value of
        // gMem.GetFreeAllocSpace() has changed from what it was at the
        // start and recalculate if it has.
        // We also count the number of threads in ML code.  Taking the
        // lock in EnterPolyCode on every RTS call turned out to be
        // expensive.
        POLYUNSIGNED freeSpace = 0;
        unsigned threadsInML = 0;
        for (unsigned j = 0; j < taskArraySize; j++)
        {
            TaskData *taskData = taskArray[j];
            if (taskData)
            {
                // This gets the values last time it was in the RTS.
                PolyWord *limit = taskData->allocLimit, *ptr = taskData->allocPointer;
                if (limit < ptr && (POLYUNSIGNED)(ptr-limit) < taskData->allocSize)
                    freeSpace += ptr-limit;
                if (taskData->inML) threadsInML++;
            }
        }
        // Add the space in the allocation areas after calculating the sizes for the
        // threads in case a thread has allocated some more.
        freeSpace += gMem.GetFreeAllocSpace();
        globalStats.updatePeriodicStats(freeSpace, threadsInML);
    }
    schedLock.Unlock();
    // We are about to return normally.  Stop any crowbar function
    // and wait until it stops.
    shutdownLock.Lock();
    if (crowbarRunning)
    {
        crowbarLock.Signal();
        shutdownLock.Unlock();
        // Wait for the thread to terminate.
#if (defined(HAVE_PTHREAD))
        pthread_join(crowBarThreadId, NULL);
#elif defined(HAVE_WINDOWS_H)
        WaitForSingleObject(hCrowBarThread, 10000);
#endif
    }
    else shutdownLock.Unlock(); // So it's always unlocked when it's destroyed.
    finish(exitResult); // Close everything down and exit.
}

// Create a new thread.  Returns the ML thread identifier object if it succeeds.
// May raise an exception.
Handle Processes::ForkThread(TaskData *taskData, Handle threadFunction,
                           Handle args, PolyWord flags, PolyWord stacksize)
{
    if (singleThreaded)
        raise_exception_string(taskData, EXC_thread, "Threads not available");

    try {
        // Create a taskData object for the new thread
        TaskData *newTaskData = machineDependent->CreateTaskData();
        // We allocate the thread object in the PARENT's space
        Handle threadId = alloc_and_save(taskData, sizeof(ThreadObject) / sizeof(PolyWord), F_MUTABLE_BIT);
        newTaskData->threadObject = (ThreadObject*)DEREFHANDLE(threadId);
        newTaskData->threadObject->index = TAGGED(0);
        newTaskData->threadObject->flags = flags; // Flags
        newTaskData->threadObject->threadLocal = TAGGED(0); // Empty thread-local store
        newTaskData->threadObject->requestCopy = TAGGED(0); // Cleared interrupt state
        newTaskData->threadObject->mlStackSize = stacksize;
        for (unsigned i = 0; i < sizeof(newTaskData->threadObject->debuggerSlots)/sizeof(PolyWord); i++)
            newTaskData->threadObject->debuggerSlots[i] = TAGGED(0);

        unsigned thrdIndex;
        schedLock.Lock();
        // Before forking a new thread check to see whether we have been asked
        // to exit.  Processes::Exit sets the current set of threads to exit but won't
        // see a new thread.
        if (taskData->requests == kRequestKill)
        {
            schedLock.Unlock();
            // Raise an exception although the thread may exit before we get there.
            raise_exception_string(taskData, EXC_thread, "Thread is exiting");
        }

        // See if there's a spare entry in the array.
        for (thrdIndex = 0;
             thrdIndex < taskArraySize && taskArray[thrdIndex] != 0;
             thrdIndex++);

        if (thrdIndex == taskArraySize) // Need to expand the array
        {
            TaskData **newArray =
                (TaskData **)realloc(taskArray, sizeof(TaskData *)*(taskArraySize+1));
            if (newArray)
            {
                taskArray = newArray;
                taskArraySize++;
            }
            else
            {
                delete(newTaskData);
                schedLock.Unlock();
                raise_exception_string(taskData, EXC_thread, "Too many threads");
            }
        }
        // Add into the new entry
        taskArray[thrdIndex] = newTaskData;
        newTaskData->threadObject->index = TAGGED(thrdIndex); // Set to the index
        schedLock.Unlock();

        newTaskData->stack = gMem.NewStackSpace(machineDependent->InitialStackSize());
        if (newTaskData->stack == 0)
        {
            delete(newTaskData);
            raise_exception_string(taskData, EXC_thread, "Unable to allocate thread stack");
        }

        // Allocate anything needed for the new stack in the parent's heap.
        // The child still has inMLHeap set so mustn't GC.
        newTaskData->InitStackFrame(taskData, threadFunction, args);

        // Now actually fork the thread.
        bool success = false;
        schedLock.Lock();
#ifdef HAVE_PTHREAD
        success = pthread_create(&newTaskData->threadId, NULL, NewThreadFunction, newTaskData) == 0;
#elif defined(HAVE_WINDOWS_H)
        newTaskData->threadHandle =
            CreateThread(NULL, 0, NewThreadFunction, newTaskData, 0, NULL);
        success = newTaskData->threadHandle != NULL;
#endif
        if (success)
        {
            schedLock.Unlock();

            if (debugOptions & DEBUG_THREADS)
                Log("THREAD: Forking new thread %p from thread %p\n", newTaskData, taskData);

            return threadId;
        }
        // Thread creation failed.
        taskArray[thrdIndex] = 0;
        delete(newTaskData);
        schedLock.Unlock();

        if (debugOptions & DEBUG_THREADS)
            Log("THREAD: Fork from thread %p failed\n", taskData);

        raise_exception_string(taskData, EXC_thread, "Thread creation failed");
    }
    catch (std::bad_alloc &) {
            raise_exception_string(taskData, EXC_thread, "Insufficient memory");
    }
}

// ForkFromRTS.  Creates a new thread from within the RTS.  This is currently used
// only to run a signal function.
bool Processes::ForkFromRTS(TaskData *taskData, Handle proc, Handle arg)
{
    try {
        (void)ForkThread(taskData, proc, arg, TAGGED(PFLAG_SYNCH), TAGGED(0));
        return true;
    } catch (IOException &)
    {
        // If it failed
        return false;
    }
}

POLYUNSIGNED PolyThreadForkThread(PolyObject *threadId, PolyWord function, PolyWord attrs, PolyWord stack)
{
    TaskData *taskData = TaskData::FindTaskForId(threadId);
    ASSERT(taskData != 0);
    taskData->PreRTSCall();
    Handle reset = taskData->saveVec.mark();
    Handle pushedFunction = taskData->saveVec.push(function);
    Handle result = 0;

    try {
        result = processesModule.ForkThread(taskData, pushedFunction, (Handle)0, attrs, stack);
    }
    catch (KillException &) {
        processes->ThreadExit(taskData); // TestSynchronousRequests may test for kill
    }
    catch (...) { } // If an ML exception is raised

    taskData->saveVec.reset(reset);
    taskData->PostRTSCall();
    if (result == 0) return TAGGED(0).AsUnsigned();
    else return result->Word().AsUnsigned();
}

// Deal with any interrupt or kill requests.
bool Processes::ProcessAsynchRequests(TaskData *taskData)
{
    bool wasInterrupted = false;
    TaskData *ptaskData = taskData;

    schedLock.Lock();

    switch (ptaskData->requests)
    {
    case kRequestNone:
        schedLock.Unlock();
        break;

    case kRequestInterrupt:
        {
            // Handle asynchronous interrupts only.
            // We've been interrupted.  
            POLYUNSIGNED attrs = ThreadAttrs(ptaskData);
            POLYUNSIGNED intBits = attrs & PFLAG_INTMASK;
            if (intBits == PFLAG_ASYNCH || intBits == PFLAG_ASYNCH_ONCE)
            {
                if (intBits == PFLAG_ASYNCH_ONCE)
                {
                    // Set this so from now on it's synchronous.
                    // This word is only ever set by the thread itself so
                    // we don't need to synchronise.
                    attrs = (attrs & (~PFLAG_INTMASK)) | PFLAG_SYNCH;
                    ptaskData->threadObject->flags = TAGGED(attrs);
                }
                ptaskData->requests = kRequestNone; // Clear this
                ptaskData->threadObject->requestCopy = TAGGED(0); // And in the ML copy
                schedLock.Unlock();
                // Don't actually throw the exception here.
                taskData->SetException(interrupt_exn);
                wasInterrupted = true;
            }
            else schedLock.Unlock();
        }
        break;

    case kRequestKill: // The thread has been asked to stop.
        schedLock.Unlock();
        throw KillException();
        // Doesn't return.
    }

#ifndef HAVE_WINDOWS_H
    // Start the profile timer if needed.
    if (profileMode == kProfileTime)
    {
        if (! ptaskData->runningProfileTimer)
        {
            ptaskData->runningProfileTimer = true;
            StartProfilingTimer();
        }
    }
    else ptaskData->runningProfileTimer = false;
    // The timer will be stopped next time it goes off.
#endif
    return wasInterrupted;
}

// If this thread is processing interrupts synchronously and has been
// interrupted clear the interrupt and raise the exception.  This is
// called from IO routines which may block.
void Processes::TestSynchronousRequests(TaskData *taskData)
{
    TaskData *ptaskData = taskData;
    schedLock.Lock();
    switch (ptaskData->requests)
    {
    case kRequestNone:
        schedLock.Unlock();
        break;

    case kRequestInterrupt:
        {
            // Handle synchronous interrupts only.
            // We've been interrupted.  
            POLYUNSIGNED attrs = ThreadAttrs(ptaskData);
            POLYUNSIGNED intBits = attrs & PFLAG_INTMASK;
            if (intBits == PFLAG_SYNCH)
            {
                ptaskData->requests = kRequestNone; // Clear this
                ptaskData->threadObject->requestCopy = TAGGED(0);
                schedLock.Unlock();
                taskData->SetException(interrupt_exn);
                throw IOException();
            }
            else schedLock.Unlock();
        }
        break;

    case kRequestKill: // The thread has been asked to stop.
        schedLock.Unlock();
        throw KillException();
        // Doesn't return.
    }
}

// Check for asynchronous or synchronous events
void Processes::TestAnyEvents(TaskData *taskData)
{
    TestSynchronousRequests(taskData);
    if (ProcessAsynchRequests(taskData))
        throw IOException();
}

// Stop.  Exit is usually called by one of the ML threads but
// in the Windows version can also be called by the GUI.
// The normal shut-down routine is to wake up the main thread
// and have it wait until all the ML threads have exited.  This
// "crow-bar" thread is intended to force a shut-down if that
// doesn't happen within 40s.  It has been increased from 20s because
// of a report that this was insufficient on a heavily loaded machine.
void Processes::CrowBarFn(void)
{
#if (defined(HAVE_PTHREAD) || defined(HAVE_WINDOWS_H))
    shutdownLock.Lock();
    crowbarRunning = true;
    if (crowbarLock.WaitFor(&shutdownLock, 40000)) // Wait for 40s
    {
        // We've been woken by the main thread.  Let it do the shutdown.
        shutdownLock.Unlock();
    }
    else
    {
#if defined(HAVE_WINDOWS_H)
        ExitProcess(1);
#else
        _exit(1); // Something is stuck.  Get out without calling destructors.
#endif
    }
#endif
}

#ifdef HAVE_PTHREAD
static void *crowBarFn(void*)
{
    processesModule.CrowBarFn();
    return 0;
}
#elif defined(HAVE_WINDOWS_H)
static DWORD WINAPI crowBarFn(LPVOID arg)
{
    processesModule.CrowBarFn();
    return 0;
}
#endif

void Processes::Exit(int n)
{
    if (singleThreaded)
        finish(n);

#if (defined(HAVE_PTHREAD) || defined(HAVE_WINDOWS_H))
    {
        // Start a crowbar thread.  This will stop everything if the main thread
        // does not reach the point of stopping within 5 seconds.
        PLocker l(&shutdownLock);
        if (!crowbarRunning)
        {
#if (defined(HAVE_PTHREAD))
            crowbarRunning = pthread_create(&crowBarThreadId, NULL, crowBarFn, 0) == 0;
#elif defined(HAVE_WINDOWS_H)
            hCrowBarThread = CreateThread(NULL, 0, crowBarFn, 0, 0, NULL);
            crowbarRunning = hCrowBarThread != NULL;
#endif
        }
    }
#endif
    // We may be in an interrupt handler with schedLock held.
    // Just set the exit request and go.
    exitResult = n;
    exitRequest = true;
    initialThreadWait.Signal(); // Wake it if it's sleeping.
}

/******************************************************************************/
/*                                                                            */
/*      catchVTALRM - handler for alarm-clock signal                          */
/*                                                                            */
/******************************************************************************/
#if !defined(HAVE_WINDOWS_H)
// N.B. This may be called either by an ML thread or by the main thread.
// On the main thread taskData will be null.
static void catchVTALRM(SIG_HANDLER_ARGS(sig, context))
{
    ASSERT(sig == SIGVTALRM);
    if (profileMode != kProfileTime)
    {
        // We stop the timer for this thread on the next signal after we end profile
        static struct itimerval stoptime = {{0, 0}, {0, 0}};
        /* Stop the timer */
        setitimer(ITIMER_VIRTUAL, & stoptime, NULL);
    }
    else {
        TaskData *taskData = processes->GetTaskDataForThread();
        handleProfileTrap(taskData, (SIGNALCONTEXT*)context);
    }
}

#else /* Windows including Cygwin */
// This runs as a separate thread.  Every millisecond it checks the CPU time used
// by each ML thread and increments the count for each thread that has used a
// millisecond of CPU time.

static bool testCPUtime(HANDLE hThread, LONGLONG &lastCPUTime)
{
    FILETIME cTime, eTime, kTime, uTime;
    // Try to get the thread CPU time if possible.  This isn't supported
    // in Windows 95/98 so if it fails we just include this thread anyway.
    if (GetThreadTimes(hThread, &cTime, &eTime, &kTime, &uTime))
    {
        LONGLONG totalTime = 0;
        LARGE_INTEGER li;
        li.LowPart = kTime.dwLowDateTime;
        li.HighPart = kTime.dwHighDateTime;
        totalTime += li.QuadPart;
        li.LowPart = uTime.dwLowDateTime;
        li.HighPart = uTime.dwHighDateTime;
        totalTime += li.QuadPart;
        if (totalTime - lastCPUTime >= 10000)
        {
            lastCPUTime = totalTime;
            return true;
        }
        return false;
    }
    else return true; // Failed to get thread time, maybe Win95.
 }


void Processes::ProfileInterrupt(void)
{               
    // Wait for millisecond or until the stop event is signalled.
    while (WaitForSingleObject(hStopEvent, 1) == WAIT_TIMEOUT)        
    {
        // We need to hold schedLock to examine the taskArray but
        // that is held during garbage collection.
        if (schedLock.Trylock())
        {
            for (unsigned i = 0; i < taskArraySize; i++)
            {
                TaskData *p = taskArray[i];
                if (p && p->threadHandle)
                {
                    if (testCPUtime(p->threadHandle, p->lastCPUTime))
                    {
                        CONTEXT context;
                        SuspendThread(p->threadHandle);
                        context.ContextFlags = CONTEXT_CONTROL; /* Get Eip and Esp */
                        if (GetThreadContext(p->threadHandle, &context))
                        {
                            handleProfileTrap(p, &context);
                        }
                        ResumeThread(p->threadHandle);
                    }
                }
            }
            schedLock.Unlock();
        }
        // Check the CPU time used by the main thread.  This is used for GC
        // so we need to check that as well.
        if (testCPUtime(mainThreadHandle, lastCPUTime))
            handleProfileTrap(NULL, NULL);
    }
}

DWORD WINAPI ProfilingTimer(LPVOID parm)
{
    processesModule.ProfileInterrupt();
    return 0;
}

#endif

// Profiling control.  Called by the root thread.
void Processes::StartProfiling(void)
{
#ifdef HAVE_WINDOWS_H
    DWORD threadId;
    extern FILE *polyStdout;
    if (profilingHd)
        return;
    ResetEvent(hStopEvent);
    profilingHd = CreateThread(NULL, 0, ProfilingTimer, NULL, 0, &threadId);
    if (profilingHd == NULL)
        fputs("Creating ProfilingTimer thread failed.\n", polyStdout);
    /* Give this a higher than normal priority so it pre-empts the main
       thread.  Without this it will tend only to be run when the main
       thread blocks for some reason. */
    SetThreadPriority(profilingHd, THREAD_PRIORITY_ABOVE_NORMAL);
#else
    // In Linux, at least, we need to run a timer in each thread.
    // We request each to enter the RTS so that it will start the timer.
    // Since this is being run by the main thread while all the ML threads
    // are paused this may not actually be necessary.
    for (unsigned i = 0; i < taskArraySize; i++)
    {
        TaskData *taskData = taskArray[i];
        if (taskData)
        {
            taskData->InterruptCode();
        }
    }
    StartProfilingTimer(); // Start the timer in the root thread.
#endif
}

void Processes::StopProfiling(void)
{
#ifdef HAVE_WINDOWS_H
    if (hStopEvent) SetEvent(hStopEvent);
    // Wait for the thread to stop
    if (profilingHd) WaitForSingleObject(profilingHd, 10000);
    CloseHandle(profilingHd);
    profilingHd = NULL;
#endif
}

// Called by the ML signal handling thread.  It blocks until a signal
// arrives.  There should only be a single thread waiting here.
bool Processes::WaitForSignal(TaskData *taskData, PLock *sigLock)
{
    TaskData *ptaskData = taskData;
    // We need to hold the signal lock until we have acquired schedLock.
    schedLock.Lock();
    sigLock->Unlock();
    if (sigTask != 0)
    {
        schedLock.Unlock();
        return false;
    }
    sigTask = ptaskData;

    if (ptaskData->requests == kRequestNone)
    {
        // Now release the ML memory.  A GC can start.
        ThreadReleaseMLMemoryWithSchedLock(ptaskData);
        globalStats.incCount(PSC_THREADS_WAIT_SIGNAL);
        ptaskData->threadLock.Wait(&schedLock);
        globalStats.decCount(PSC_THREADS_WAIT_SIGNAL);
        // We want to use the memory again.
        ThreadUseMLMemoryWithSchedLock(ptaskData);
    }

    sigTask = 0;
    schedLock.Unlock();
    return true;
}

// Called by the signal detection thread to wake up the signal handler
// thread.  Must be called AFTER releasing sigLock.
void Processes::SignalArrived(void)
{
    PLocker locker(&schedLock);
    if (sigTask)
        sigTask->threadLock.Signal();
}

#ifdef HAVE_PTHREAD
// This is called when the thread exits in foreign code and
// ThreadExit has not been called.
static void threaddata_destructor(void *p)
{
    TaskData *pt = (TaskData *)p;
    pt->threadExited = true;
    // This doesn't actually wake the main thread and relies on the
    // regular check to release the task data.
}
#endif

void Processes::Init(void)
{
#ifdef HAVE_WINDOWS_H
    // Create event to wake up from IO sleeping.
    Waiter::hWakeupEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
#endif

#ifdef HAVE_PTHREAD
    pthread_key_create(&tlsId, threaddata_destructor);
#elif defined(HAVE_WINDOWS_H)
    tlsId = TlsAlloc();
#else
    singleThreaded = true;
#endif

#if defined(HAVE_WINDOWS_H) /* Windows including Cygwin. */
    // Create stop event for time profiling.
    hStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    // Get the thread handle for this thread.
    HANDLE thisProcess = GetCurrentProcess();
    DuplicateHandle(thisProcess, GetCurrentThread(), thisProcess, 
        &mainThreadHandle, THREAD_ALL_ACCESS, FALSE, 0);
#else
    // Set up a signal handler.  This will be the same for all threads.
    markSignalInuse(SIGVTALRM);
    setSignalHandler(SIGVTALRM, catchVTALRM);
#endif
}

#ifndef HAVE_WINDOWS_H
// On Linux, at least, each thread needs to run this.
void Processes::StartProfilingTimer(void)
{
    // set virtual timer to go off every millisecond
    struct itimerval starttime;
    starttime.it_interval.tv_sec = starttime.it_value.tv_sec = 0;
    starttime.it_interval.tv_usec = starttime.it_value.tv_usec = 1000;
    setitimer(ITIMER_VIRTUAL,&starttime,NULL);
}
#endif

void Processes::Stop(void)
{     
#ifdef HAVE_WINDOWS_H
    if (Waiter::hWakeupEvent) SetEvent(Waiter::hWakeupEvent);
#endif

#ifdef HAVE_WINDOWS_H
    if (Waiter::hWakeupEvent) CloseHandle(Waiter::hWakeupEvent);
    Waiter::hWakeupEvent = NULL;
#endif

#ifdef HAVE_PTHREAD
    pthread_key_delete(tlsId);
#elif defined(HAVE_WINDOWS_H)
    TlsFree(tlsId);
#endif

#if defined(HAVE_WINDOWS_H)
    /* Stop the timer and profiling threads. */
    if (hStopEvent) SetEvent(hStopEvent);
    if (profilingHd)
    {
        WaitForSingleObject(profilingHd, 10000);
        CloseHandle(profilingHd);
        profilingHd = NULL;
    }
    if (hStopEvent) CloseHandle(hStopEvent);
    hStopEvent = NULL;
    if (mainThreadHandle) CloseHandle(mainThreadHandle);
    mainThreadHandle = NULL;
#else
    profileMode = kProfileOff;
    // Make sure the timer is not running
    struct itimerval stoptime;
    memset(&stoptime, 0, sizeof(stoptime));
    setitimer(ITIMER_VIRTUAL, &stoptime, NULL);
#endif
}

void Processes::GarbageCollect(ScanAddress *process)
/* Ensures that all the objects are retained and their addresses updated. */
{   
    /* The interrupt exn */
    if (interrupt_exn != 0) {
        PolyObject *p = interrupt_exn;
        process->ScanRuntimeAddress(&p, ScanAddress::STRENGTH_STRONG);
        interrupt_exn = (PolyException*)p;
    }
    for (unsigned i = 0; i < taskArraySize; i++)
    {
        if (taskArray[i])
            taskArray[i]->GarbageCollect(process);
    }
}

void TaskData::GarbageCollect(ScanAddress *process)
{
    saveVec.gcScan(process);

    if (threadObject != 0)
    {
        PolyObject *p = threadObject;
        process->ScanRuntimeAddress(&p, ScanAddress::STRENGTH_STRONG);
        threadObject = (ThreadObject*)p;
    }
    if (blockMutex != 0)
        process->ScanRuntimeAddress(&blockMutex, ScanAddress::STRENGTH_STRONG);
    // The allocation spaces are no longer valid.
    allocPointer = 0;
    allocLimit = 0;
    // Divide the allocation size by four. If we have made a single allocation
    // since the last GC the size will have been doubled after the allocation.
    // On average for each thread, apart from the one that ran out of space
    // and requested the GC, half of the space will be unused so reducing by
    // four should give a good estimate for next time.
    if (allocCount != 0)
    { // Do this only once for each GC.
        allocCount = 0;
        allocSize = allocSize/4;
        if (allocSize < MIN_HEAP_SIZE)
            allocSize = MIN_HEAP_SIZE;
    }
    process->ScanRuntimeWord(&foreignStack);
}

// Return the number of processors.
extern unsigned NumberOfProcessors(void)
{
#if (defined(_WIN32) && ! defined(__CYGWIN__))
        SYSTEM_INFO info;
        memset(&info, 0, sizeof(info));
        GetSystemInfo(&info);
        if (info.dwNumberOfProcessors == 0) // Just in case
            info.dwNumberOfProcessors = 1;
        return info.dwNumberOfProcessors;
#elif(defined(_SC_NPROCESSORS_ONLN))
        long res = sysconf(_SC_NPROCESSORS_ONLN);
        if (res <= 0) res = 1;
        return res;
#elif(defined(HAVE_SYSCTL) && defined(CTL_HW) && defined(HW_NCPU))
        static int mib[2] = { CTL_HW, HW_NCPU };
        int nCPU = 1;
        size_t len = sizeof(nCPU);
        if (sysctl(mib, 2, &nCPU, &len, NULL, 0) == 0 && len == sizeof(nCPU))
             return nCPU;
        else return 1;
#else
        // Can't determine.
        return 1;
#endif
}

// Return the number of physical processors.  If hyperthreading is
// enabled this returns less than NumberOfProcessors.  Returns zero if
// it cannot be determined.
// This can be used in Cygwin as well as native Windows.
#if (defined(HAVE_SYSTEM_LOGICAL_PROCESSOR_INFORMATION))
typedef BOOL (WINAPI *GETP)(SYSTEM_LOGICAL_PROCESSOR_INFORMATION*, PDWORD);

// Windows - use GetLogicalProcessorInformation if it's available.
static unsigned WinNumPhysicalProcessors(void)
{
    GETP getProcInfo = (GETP) GetProcAddress(GetModuleHandle(_T("kernel32")), "GetLogicalProcessorInformation");
    if (getProcInfo == 0) return 0;

    // It's there - use it.
    SYSTEM_LOGICAL_PROCESSOR_INFORMATION *buff = 0;
    DWORD space = 0;
    while (getProcInfo(buff, &space) == FALSE)
    {
        if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
        {
            free(buff);
            return 0;
        }
        free(buff);
        buff = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc(space);
        if (buff == 0) return 0;
    }
    // Calculate the number of full entries in case it's truncated.
    unsigned nItems = space / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
    unsigned numProcs = 0;
    for (unsigned i = 0; i < nItems; i++)
    {
        if (buff[i].Relationship == RelationProcessorCore)
            numProcs++;
    }
    free(buff);
    return numProcs;
}
#endif

// Read and parse /proc/cpuinfo
static unsigned LinuxNumPhysicalProcessors(void)
{
    // Find out the total.  This should be the maximum.
    unsigned nProcs = NumberOfProcessors();
    // If there's only one we don't need to check further.
    if (nProcs <= 1) return nProcs;
    long *cpus = (long*)calloc(nProcs, sizeof(long));
    if (cpus == 0) return 0;

    FILE *cpuInfo = fopen("/proc/cpuinfo", "r");
    if (cpuInfo == NULL) { free(cpus); return 0; }

    char line[40];
    unsigned count = 0;
    while (fgets(line, sizeof(line), cpuInfo) != NULL)
    {
        if (strncmp(line, "core id\t\t:", 10) == 0)
        {
            long n = strtol(line+10, NULL, 10);
            unsigned i = 0;
            // Skip this id if we've seen it already
            while (i < count && cpus[i] != n) i++;
            if (i == count) cpus[count++] = n;
        }
        if (strchr(line, '\n') == 0)
        {
            int ch;
            do { ch = getc(cpuInfo); } while (ch != '\n' && ch != EOF);
        }
    }

    fclose(cpuInfo);
    free(cpus);
    return count;
}

extern unsigned NumberOfPhysicalProcessors(void)
{
    unsigned numProcs = 0;
#if (defined(HAVE_SYSTEM_LOGICAL_PROCESSOR_INFORMATION))
    numProcs = WinNumPhysicalProcessors();
    if (numProcs != 0) return numProcs;
#endif
#if (defined(HAVE_SYSCTLBYNAME) && defined(HAVE_SYS_SYSCTL_H))
    // Mac OS X
    int nCores;
    size_t len = sizeof(nCores);
    if (sysctlbyname("hw.physicalcpu", &nCores, &len, NULL, 0) == 0)
        return (unsigned)nCores;
#endif
    numProcs = LinuxNumPhysicalProcessors();
    if (numProcs != 0) return numProcs;
    // Any other cases?
    return numProcs;
}