This file is indexed.

/usr/lib/perl5/forks.pm is in libforks-perl 0.34-1build3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
package forks;   # make sure CPAN picks up on forks.pm
$VERSION = '0.34';

# Allow external modules to defer shared variable init at require

$DEFER_INIT_BEGIN_REQUIRE = 0 unless $DEFER_INIT_BEGIN_REQUIRE;

package
    threads; # but in fact we're masquerading as threads.pm

# Make sure we have version info for this module
# Set flag to indicate that we're really the original threads implementation
# Set flag to indicate that we're not really the original threads implementation
# Flag whether or not module is loaded in namespace override mode (e.g. threads.pm)
# Be strict from now on

BEGIN {
    $VERSION = '1.77';
    $threads        = $threads        = 1; # twice to avoid warnings
    $forks::threads = $forks::threads = 1; # twice to avoid warnings
    $forks::threads_override = $forks::threads_override = 0; # twice to avoid warnings
}

# Standard forks behavior (extra features), or emulate threads to-the-letter

BEGIN {
    if ($forks::threads_override) {
        $forks::threads_native_emulation = 1;
    } elsif (exists $ENV{'THREADS_NATIVE_EMULATION'}) {
        $ENV{'THREADS_NATIVE_EMULATION'} =~ m#^(.*)$#s;
        $forks::threads_native_emulation = $1 ? 1 : 0;
    } else {
        $forks::threads_native_emulation = 0;
    }
    *forks::THREADS_NATIVE_EMULATION = sub { $forks::threads_native_emulation };
}

# Use strict pragma
# Use warnings pragma
# Register 'threads' namespace with warnings (if not already present)
# Make sure we can die with lots of information

use strict;
use warnings;
use warnings::register;
use Carp ();

#---------------------------------------------------------------------------
# Set when to execute check and end blocks

BEGIN {
    if ($^C) {
        eval "CHECK { _CHECK() }";
    } elsif (defined &DB::DB) {
        # TODO: no end block for now, as debugger halts on it (ignoring $DB::inhibit_exit)
    } else {
        $] < 5.008 ? eval "END { eval{ _END() } }" : eval "END { _END() }";
    }
} #BEGIN

# Fake that threads.pm was really loaded, before loading any other modules

BEGIN {
    my $module = 'forks';
    if (defined $INC{'forks.pm'}) {
        $INC{'threads.pm'} ||= $INC{'forks.pm'};
    } elsif (defined $INC{'threads.pm'} && $forks::threads_override) {
        $module = 'threads';
        $INC{'forks.pm'} ||= $INC{'threads.pm'}
    } elsif (defined $INC{'threads.pm'} && !$forks::threads_override) {
        die( "Can not mix 'use forks' with real 'use threads'" )
    }

    $module = 'threads' if eval{forks::THREADS_NATIVE_EMULATION()};
    Carp::carp "Warning, $module\::shared has already been loaded"
        if defined $INC{'forks/shared.pm'};
}

# Load signal handler libraries

BEGIN {
    require sigtrap;
    require forks::signals;
}

# Import additional scalar methods for refs and objects
# Load library to set temp dir for forks data
# Load library that to support unblessing objects

use Scalar::Util qw(reftype blessed refaddr);
use File::Spec;
use forks::Devel::Symdump; # Perl 5.10.x patch for Devel::Symdump 2.08
use Acme::Damn ();

# Set constant for IPC temp dir
# Set constant for IPC temp thread signal notifications

use constant ENV_ROOT   => File::Spec->tmpdir().'/perlforks';
use constant ENV_SIGNALS => ENV_ROOT.'/signals';

# Set constants for threads->list() operations: all, running, and joinable

use constant all      => ();
use constant running  => 1;
use constant joinable => 0;

# Set constants for threads exit

use constant EXIT_THREAD_ONLY => 'thread_only';
use constant EXIT_THREADS_ONLY => 'threads_only';

# (bug?) Perl 5.11+ each function may not correctly set hash iterator when using refs as keys
use constant RESET_EACH_ITER => $] >= 5.011;

#---------------------------------------------------------------------------
# Modify Perl's Config.pm to simulate that it was built with ithreads

BEGIN {
    require Config;
    my $h = tied %Config::Config;
    $h->{useithreads} = 1;
}

#---------------------------------------------------------------------------

# Global debug flag
# Global socket server Nice value
# Global CHLD force IGNORE flag
# Global UNIX socket flag
# Global INET socket IP mask regex value
# Do this at compile time
#  If there is a THREADS_DEBUG specification
#   Untaint value
#   Set its value
#   Make sure access is done with the DEBUG sub
#  Else (we never need any debug info)
#   Make DEBUG a false constant: debugging code should be optimised away
#  If there is a THREADS_SOCKET_UNIX specification
#   Set its value
#   Make sure socket is available; die if non-socket object exists
#   Remove existing socket file if defined
#   Make sure access is done with the THREADS_UNIX sub
#  Else 
#   Make THREADS_UNIX a false constant: default to INET sockets
#  If there is a THREADS_IP_MASK specification
#   Set its value
#  Else
#   Use default localhost mask
#  If there is a THREADS_DAEMON_MODEL specification
#   Enable integrated threads (server process child of main thread)
#  Else
#   Enable normal threads (server process parent of main thread)
#  If there is a PERL5_ITHREADS_STACK_SIZE specification
#   Set this as the new default size
#  Else
#   Set to the system default size (0 == use system default)

my $DEBUG;
my $SERVER_NICE;
my $FORCE_SIGCHLD_IGNORE;
my $THREADS_UNIX;
my $INET_IP_MASK;
my $THREADS_INTEGRATED_MODEL;
my $ITHREADS_STACK_SIZE;

BEGIN {
    if (exists $ENV{'THREADS_DEBUG'}) {
        $ENV{'THREADS_DEBUG'} =~ m#^(.*)$#s;
        $DEBUG = $1;
    } else {
        $DEBUG = 0;
    }
    *DEBUG = sub () { $DEBUG };

    if (exists $ENV{'THREADS_NICE'}) {
        $ENV{'THREADS_NICE'} =~ m#^(.*)$#s;
        $SERVER_NICE = $1;
    } else {
        $SERVER_NICE = 0;
    }

    if (exists $ENV{'THREADS_SIGCHLD_IGNORE'}) {
        $ENV{'THREADS_SIGCHLD_IGNORE'} =~ m#^(.*)$#s;
        $FORCE_SIGCHLD_IGNORE = $1;
    } else {
        $FORCE_SIGCHLD_IGNORE = 0;
    }

    my $threads_socket_unix = '/var/tmp/perlforks.';
    if (defined $ENV{'THREADS_SOCKET_UNIX'} && $ENV{'THREADS_SOCKET_UNIX'} ne "") {
        #$ENV{'THREADS_SOCKET_UNIX'} =~ m#^(.*)$#s;
        $THREADS_UNIX = $threads_socket_unix;
    } else {
        $THREADS_UNIX = 0;
    }

    if (exists $ENV{'THREADS_IP_MASK'}) {
        $ENV{'THREADS_IP_MASK'} =~ m#^(.*)$#s;
        $INET_IP_MASK = $1;
    } else {
        $INET_IP_MASK = '^127\.0\.0\.1$';
    }

    if (exists $ENV{'THREADS_DAEMON_MODEL'}) {
        $ENV{'THREADS_DAEMON_MODEL'} =~ m#^(.*)$#s;
        $THREADS_INTEGRATED_MODEL = $1 ? 0 : 1;
    } else {
        $THREADS_INTEGRATED_MODEL = 1;
    }

    if (exists $ENV{'PERL5_ITHREADS_STACK_SIZE'}) {
        $ENV{'PERL5_ITHREADS_STACK_SIZE'} =~ m#^(\d+)$#s;
        $ITHREADS_STACK_SIZE = $1;
    } else {
        $ITHREADS_STACK_SIZE = 0;
    }
} #BEGIN

# Load the XS stuff

require XSLoader;
XSLoader::load( 'forks',$forks::VERSION );

# Make sure we can do sockets and have the appropriate constants
# Make sure we can do select() on multiple sockets
# Make sure we have the necessary POSIX constants
# Make sure that we can freeze and thaw data structures
# Allow for chainable child reaping functions
# Enable hi-res time

use Socket     qw(SOMAXCONN);
use IO::Socket ();
use IO::Select ();
use POSIX      qw(WNOHANG
    BUFSIZ O_NONBLOCK F_GETFL F_SETFL
    SIG_BLOCK SIG_UNBLOCK SIGCHLD SIGKILL
    ECONNABORTED ECONNRESET EAGAIN EINTR EWOULDBLOCK ETIMEDOUT
    SA_RESTART SA_NOCLDSTOP
    WIFEXITED WIFSIGNALED);
use Storable   ();
use Time::HiRes qw(time);
use List::MoreUtils;

# Flag whether or not forks has initialized the server process
# Thread local query server object
# The port on which the thread server is listening
# The process id in which the shared variables are stored
# The main thread process id
# Initialize thread local hash (key: pid) whether this process is a thread
# Initialize local flag whether main thread received ABRT signal
# Initialize local flag whether main thread exited due to ABRT signal
# Initialize local flag whether main thread should be signalled with ABRT on server shutdown
# Initialize hash (key: pid) of child thread PIDs
# Thread local flag whether we're shutting down
# Thread local flag whether we're shutting down in END block
# Thread local flag whether we're shut down

my $HANDLED_INIT = 0;
my $QUERY;
my $PORT;
my $SHARED;
my $PID_MAIN_THREAD;
my %ISATHREAD;
my $MAIN_ABRT_HANDLED = 0;
my $MAIN_EXIT_WITH_ABRT = 0;
my $MAIN_EXIT_NO_ABRT = 0;
my %CHILD_PID;
my $SHUTTING_DOWN = 0;
my $SHUTTING_DOWN_END = 0;
my $SHUTDOWN = 0;

# Initialize the flag that indicates that we're still running
# Initialize value that stores the desired application exit value
# Initialize the number of bytes to read at a time
# List of signals that forks intelligently monitors and traps to insure inter-thread signal stability
# Initialize hash (key: sig name) of base not-defined signal behavior to use with forks::signals
# Initialize hash (key: sig name) of base defined signal behavior to use with forks::signals
# Pseudo-signal mask indicating signals to handle when thread finished current server message handling
# Initialize flag that indicates whether thread is send data with shared process
# Initialize flag that indicates whether thread is recv data with shared process
# Initialize variable for shared server received data
# Boolean indicating whether or not platform requires a custom CHLD handler
# Max sleep time of main server loop before looping once
# Initialize hash (key: client) with info to be written to client threads
# Initialize hash (key: client) with clients that we're done with
# Initialize the "thread local" thread id
# Initialize the pid of the thread
# Return context of thread (possible values are same as those of CORE::wantarray)
# Initialize hash (key: package) with code references of CLONE subroutines
# Initialize hash (key: package) with code references of CLONE_SKIP subroutines
# Initialize hash (key: package) with object references for CLONE_SKIP-enabled classes

my $RUNNING = 1;
my $EXIT_VALUE;
my $BUFSIZ  = BUFSIZ;
my @TRAPPED_SIGNAL;
BEGIN {
    foreach my $signal (qw(HUP INT PIPE TERM USR1 USR2 ABRT EMT QUIT TRAP)) {
        push @TRAPPED_SIGNAL, $signal if grep(/^$signal$/,
            split(/\s+/, $Config::Config{sig_name}));
    }
}
my %THR_UNDEFINED_SIG = map { $_ => \&_sigtrap_handler_undefined } @TRAPPED_SIGNAL;
my %THR_DEFINED_SIG = map { $_ => \&_sigtrap_handler_defined } @TRAPPED_SIGNAL;
my @DEFERRED_SIGNAL = ();
$threads::SEND_IN_PROGRESS = 0;
$threads::RECV_IN_PROGRESS = 0;
$threads::RECV_DATA = '';
my $CUSTOM_SIGCHLD = 0;
my $MAX_POLL_SLEEP = 60;    #seconds
my %WRITE;
my %DONEWITH;
my $TID;
my $PID;
my $THREAD_CONTEXT;
my %CLONE;
our %CLONE_SKIP;
our %CLONE_SKIP_REF;

# Initialize the next thread ID to be issued
# Initialize hash (key: tid) with the thread id to client object translation
# Initialize hash (key: client) with the client object to thread id translation
# Initialize hash (key: tid) with the thread id to process id translation
# Initialize hash (key: pid) with the process id to thread id translation
# Initialize hash (key: ppid) with the parent pid to child tid queue (value: array ref)
# Initialize hash (key: tid) with the thread id to thread join context translation
# Initialize hash (key: tid) with the thread id to thread stack size translation

my $NEXTTID = 0;
my %TID2CLIENT;
my %CLIENT2TID;
my %TID2PID;
my %PID2TID;
my %PPID2CTID_QUEUE;
my %TID2CONTEXT;
my %TID2STACKSIZE;

# Initialize flag with global thread exit method (1=thread; 0=check %THREAD_EXIT)
# Initialize hash (key: tid) with threads that should threads->exit() on exit()
# Initialize scalar with tid's (comma-separated) that have been detached
# Initialize hash (key: tid) with detached threads are still running
# Initialize hash (key: tid) with results from threads
# Initialize hash (key: tid) with terminal errors from threads
# Initialize hash (key: tid) with threads that have not yet been joined

my $THREADS_EXIT = 0;
my %THREAD_EXIT;
my $DETACHED = '';
my %DETACHED_NOTDONE;
my %RESULT;
my %ERROR;
my %NOTJOINED;

# Initialize hash (key: ppid) with clients blocking of ppid->ctid conversion
# Initialize hash (key: tid) with clients blocking for join() result
# Initialize period (seconds) of BLOCKING_JOIN check (abnormal thread death protection)
# Initialize time of next BLOCKING_JOIN check

my %BLOCKING_PPID2CTID_QUEUE;
my %BLOCKING_JOIN;
my $BLOCKING_JOIN_CHECK_PERIOD = 15;
my $BLOCKING_JOIN_CHECK_TS_NEXT = 0;

# Initialize hash (key: fq sub) with code references to tie subroutines
# List with objects of shared (tied) variables
# Ordinal number of next shared (tied) variable

my %DISPATCH;
my @TIED;
my $NEXTTIED = 1;

# Initialize list (key: ordinal) of threads that have the lock for a variable
# Initialize hash (key: ordinal) of TID caller information from the (non-recursive) lock()
# Initialize list (key: ordinal) of threads that have a recursive lock
# Initialize list (key: ordinal) of threads that want to lock a variable
# Initialize list (key: ordinal) of threads are waiting in cond_wait
# Initialize hash (key: ordinal) of threads are waiting in cond_timedwait
# Initialize scalar representing unique ID of each timed event
# Initialize list (order: expiration time) representing a sorted version (pseudo-index) of %TIMEDWAITING
# Initialize scalar indicating when %TIMEDWAITING has changed and @TIMEDWAITING_IDX should be recalculated
# Initialize list (key: ordinal; subkey: tid) of TIMEDWAITING events that have timed out

my @LOCKED;
my %TID2LOCKCALLER;
my @RECURSED;
my @LOCKING;
my @WAITING;
my %TIMEDWAITING;
my $TIMEDWAITING_ID = 0;
my @TIMEDWAITING_IDX;
my $TIMEDWAITING_IDX_EXPIRED = 0;
my @TIMEDWAITING_EXPIRED;

# Initialize hash (key: tid, value=signal) with clients to send sigals to

my %TOSIGNAL;

# Flag indicating whether deadlock detection enabled (default: disabled)
# Deadlock detection period (0 => sync detection; else async detect every N sec)
# Time of next deadlock detection event, if in asynchronous mode
# Initialize hash (key: tid; value: tid of blocker) with clients that are deadlocked
# Flag of whether server should terminate one thread of each deadlocked thread pair
# Signal to use to kill deadlocked processes

my $DEADLOCK_DETECT = 0;
my $DEADLOCK_DETECT_PERIOD = 0;
my $DEADLOCK_DETECT_TS_NEXT = 0;
my %DEADLOCKED;
my $DEADLOCK_RESOLVE = 0;
my $DEADLOCK_RESOLVE_SIG = SIGKILL;

# Create packed version of undef
# Create packed version of zero-length string
# Create packed version of false
# Create packed version of true
# Create packed version of empty list

my $undef = _pack_response( [undef],  );
my $defined = _pack_response( [''],  );
my $false = _pack_response( [0], '__boolean' );
my $true  = _pack_response( [1], '__boolean' );
my $empty = _pack_response( [],  );

# Miscellaneous command-related constants
# Command filters (closures) for optimized request/response handling

my %cmd_filter;
my @cmd_filtered;
my @cmd_num_to_filter;
my @cmd_num_to_type;
my %cmd_type_to_num;
BEGIN {
    use constant CMD_FLTR_REQ    => 0;
    use constant CMD_FLTR_RESP   => 1;
    use constant CMD_FLTR_ENCODE => 0;
    use constant CMD_FLTR_DECODE => 1;

    use constant CMD_TYPE_DEFAULT    => 0;   #entire content is frozen
    use constant CMD_TYPE_INTERNAL   => 1;   #msg has a custom filter

    use constant MSG_LENGTH_LEN                  => 4;
    use constant CMD_TYPE_IDX                    => 0;
    use constant CMD_TYPE_LEN                    => 1;
    use constant CMT_TYPE_FROZEN_CONTENT_IDX     => 1;
    use constant CMD_TYPE_INTERNAL_SUBNAME_IDX   => 1;
    use constant CMD_TYPE_INTERNAL_SUBNAME_LEN   => 2;
    use constant CMD_TYPE_INTERNAL_CONTENT_IDX   => 3;
    %cmd_filter = (  #pack: 1 arrayref input param; unpack: 1 scalar input param; pack/unpack: list output
        __boolean   => [    #client-to-server
            [   #request
                sub { $_[0]->[0] ? '1' : '0'; }, #pack
                sub { $_[0]; }  #unpack
            ],
            [   #response
                sub { $_[0]->[0] ? '1' : '0'; }, #pack
                sub { $_[0]; }  #unpack
            ],
        ],
    );
    %cmd_filter = (  #pack: 1 arrayref input param; unpack: 1 scalar input param; pack/unpack: list output
        %cmd_filter,
        _lock   => [    #client-to-server
            [   #request
                sub { pack('IIa*', @{$_[0]}[0..2]); }, #pack
                sub { unpack('IIa*', $_[0]); }  #unpack
            ],
            $cmd_filter{__boolean}->[CMD_FLTR_RESP]   #response
        ],
        _unlock   => [    #client-to-server
            [   #request
                sub { pack('I', $_[0]->[0]); }, #pack
                sub { unpack('I', $_[0]); }  #unpack
            ],
            $cmd_filter{__boolean}->[CMD_FLTR_RESP]   #response
        ],
    );
    @cmd_filtered = sort { lc($a) cmp lc($b) } keys %cmd_filter;
    for (my $i = 0; $i < scalar @cmd_filtered; $i++) {
        $cmd_num_to_filter[$i] = $cmd_filter{$cmd_filtered[$i]};
        $cmd_num_to_type[$i] = $cmd_filtered[$i];
        $cmd_type_to_num{$cmd_filtered[$i]} = $i;
    }
} #BEGIN

# Make sure that equality works on thread objects

use overload
 '==' => \&equal,
 '!=' => \&nequal,
 'fallback' => 1,
;

# Keep reference to pre-existing exit function
my $old_core_global_exit;
BEGIN {
    $old_core_global_exit = sub { CORE::exit(@_) };
}

# Create new() -> create() equivalence
# Initialize thread server at runtime, in case import was skipped

*create = \&new; create() if 0; # to avoid warning
_init() unless $forks::DEFER_INIT_BEGIN_REQUIRE;

# Functions to allow external modules an API hook to specific runtime states
# These may be used to build a new CORE::GLOBAL::fork state
# General rule is that forks.pm will never define anything but CORE::fork
#  in _fork function, so this is the function to overload if you must
#  completely handle the core fork event; otherwise, all other methods
#  should be referenced and called like:
#    my $_old_fork_post_child = \&threads::_fork_post_child;
#    *threads::_fork_post_child = sub {
#        $_old_fork_post_child->();
#        ...
#    }
#  when building a new CORE::GLOBAL::fork state.
#  See forks.pm CORE::GLOBAL::fork definition as an example.

# Block all process signals when forking, to insure most stable behavior.
my $_fork_block_sigset;
BEGIN {
    $_fork_block_sigset = POSIX::SigSet->new();
    $_fork_block_sigset->fillset();
}

sub _fork_pre {

# Block all signals during fork to prevent interruption

    POSIX::sigprocmask(SIG_BLOCK, $_fork_block_sigset);
} #_fork_pre
sub _fork { return CORE::fork; } #_fork
sub _fork_post_parent {

# Restore signals blocked during fork

    POSIX::sigprocmask(SIG_UNBLOCK, $_fork_block_sigset);
} #_fork_post_parent
sub _fork_post_child {

# Restore signals blocked during fork
# Reset some important state variables
# Reset CORE::GLOBAL::exit(); will be redefined in _init_thread

    POSIX::sigprocmask(SIG_UNBLOCK, $_fork_block_sigset);
    delete $ISATHREAD{$$};
    undef( $TID );
    undef( $PID );
    {
        no warnings 'redefine';
        *CORE::GLOBAL::exit = $old_core_global_exit;
    }
} #_fork_post_child

# Overload global fork for best protection against external fork.

BEGIN {
    no warnings 'redefine';
    *CORE::GLOBAL::fork = *CORE::GLOBAL::fork = sub {
    
# Perform the fork
# Handle post-fork in parent and child processes, if fork was successful
# Return the forked pid
        
        _fork_pre(@_);
        my $pid = _fork(@_);
        if (defined $pid) {
            if ($pid == 0) { #in child
                _fork_post_child(@_);
            } else {
                _fork_post_parent(@_);
            }
        }
        return $pid;
    };
} #BEGIN

# Overload global, Time::HiRes sleep functions to reduce CHLD signal side-effects
# Define flag toggled when REAPER has been called but user hasn't defined handler

our $IFNDEF_REAPER_CALLED = 0;
BEGIN {
    no warnings 'redefine';

# Store Time::HiRes sleep function for internal use

    my $proto = prototype 'CORE::sleep';
    my $sleep = *sleep = *sleep = \&Time::HiRes::sleep;
    my $sub = sub {

# Get requested sleep time
# Initialize a few variables
# Localize signal indicator for use only for this system call
# While sleep time hasn't yet been exhausted
#  Calculate remaining sleep time
#  Reset signal indicator
#  Sleep and store total time slept
#  Exit loop if sleep exited for some reason other than a CHLD signal
# Return total time slept

        my $s = shift;
        my $t = 0;
        my $f = 0;
        my $sig;
        local $IFNDEF_REAPER_CALLED;
        while ($s - $t > 0) {
            $s -= $t;
            $IFNDEF_REAPER_CALLED = 0;
            $f += $t = $sleep->($s);
            last unless $IFNDEF_REAPER_CALLED;
        }
        return sprintf("%.0f", $f); 
    };
    Scalar::Util::set_prototype(\&{$sub}, $proto);
    *CORE::GLOBAL::sleep = *CORE::GLOBAL::sleep = $sub;

# Generate same function wrapper for Time::HiRes sleep, usleep, and nanosleep.
# For usleep and nanosleep, only overload if they are defined.

    $proto = prototype 'Time::HiRes::sleep';
    $sub = sub {
        my $s = shift;
        my $t = 0;
        my $f = 0;
        my $sig;
        local $IFNDEF_REAPER_CALLED;
        while ($s - $t > 0) {
            $s -= $t;
            $IFNDEF_REAPER_CALLED = 0;
            $f += $t = $sleep->($s);
            last unless $IFNDEF_REAPER_CALLED;
        }
        return $f; 
    };
    Scalar::Util::set_prototype(\&{$sub}, $proto);
    *Time::HiRes::sleep = *Time::HiRes::sleep = $sub;

    if (&Time::HiRes::d_usleep
        && defined(my $t = eval { Time::HiRes::usleep(0) }) && !$@) {
        $proto = prototype 'Time::HiRes::usleep';
        my $usleep = \&Time::HiRes::usleep;
        $sub = sub {
            my $s = shift;
            my $t = 0;
            my $f = 0;
            my $sig;
            local $IFNDEF_REAPER_CALLED;
            while ($s - $t > 0) {
                $s -= $t;
                $IFNDEF_REAPER_CALLED = 0;
                $f += $t = $usleep->($s);
                last unless $IFNDEF_REAPER_CALLED;
            }
            return $f; 
        };
        Scalar::Util::set_prototype(\&{$sub}, $proto);
        *Time::HiRes::usleep = *Time::HiRes::usleep = $sub;
    }

    if (&Time::HiRes::d_nanosleep
        && defined(my $t = eval { Time::HiRes::nanosleep(0) }) && !$@) {
        $proto = prototype 'Time::HiRes::nanosleep';
        my $nanosleep = \&Time::HiRes::nanosleep;
        $sub = sub {
            my $s = shift;
            my $t = 0;
            my $f = 0;
            my $sig;
            local $IFNDEF_REAPER_CALLED;
            while ($s - $t > 0) {
                $s -= $t;
                $IFNDEF_REAPER_CALLED = 0;
                $f += $t = $nanosleep->($s);
                last unless $IFNDEF_REAPER_CALLED;
            }
            return $f; 
        };
        Scalar::Util::set_prototype(\&{$sub}, $proto);
        *Time::HiRes::nanosleep = *Time::HiRes::nanosleep = $sub;
    }
} #BEGIN

#---------------------------------------------------------------------------

# class methods

#---------------------------------------------------------------------------
#  IN: 1 class
#      2 subroutine reference of sub to start execution with
#      3..N any parameters to be passed
# OUT: 1 instantiated object

sub new {

# Obtain the class
# Obtain the subroutine reference
# Initialize some local vars
# Parse stack_size of this object (if new called with object reference)
# If sub is a hash ref
#  Assume thread-specific params were defined
#  Obtain the actual subroutine
#  Parse stack_size
#  Parse thread context (presidence given to param over implicit context)
#  Parse thread exit behavior
# Else
#  Store implicit thread context
    my $class = shift;
    my $sub = shift;
    my ($param, $stack_size, $thread_context, $thread_exit);
    if (ref($class) && defined( my $size = $class->get_stack_size )) {
        $stack_size = $size;
    }
    if (ref($sub) eq 'HASH') {
        $param = $sub;
        $sub = shift;
        if (exists $param->{'stack_size'} && defined $param->{'stack_size'}) {
            $stack_size = $param->{'stack_size'};
        }
        if (exists $param->{'stack'} && defined $param->{'stack'}) {
            $stack_size = $param->{'stack'};
        }
        if ((exists $param->{'context'} && $param->{'context'} =~ m/^list|array$/o)
            || (exists $param->{'list'} && $param->{'list'} || (exists $param->{'array'} && $param->{'array'})))
        {
            $thread_context = 1;
        } elsif ((exists $param->{'context'} && $param->{'context'} eq 'scalar')
            || (exists $param->{'scalar'} && $param->{'scalar'}))
        {
            $thread_context = 0;
        } elsif ((exists $param->{'context'} && $param->{'context'} eq 'void')
            || (exists $param->{'void'} && $param->{'void'}))
        {
            $thread_context = undef;
        } else {
            $thread_context = CORE::wantarray;
        }
        
        if (exists $param->{'exit'}) {
            if ($param->{'exit'} eq EXIT_THREAD_ONLY) {
                $thread_exit = EXIT_THREAD_ONLY;
            } elsif ($param->{'exit'} eq EXIT_THREADS_ONLY) {
                $thread_exit = EXIT_THREADS_ONLY;
            }
        }
    } else {
        $thread_context = CORE::wantarray;
    }

# If it is not a code ref yet (other refs will bomb later)
#  Make the subroutine fully qualified if it is not yet
#  Turn the name into a reference

    unless (ref($sub)) {
        $sub = caller().'::'.$sub unless $sub =~ m#::#;
        $sub = \&{$sub};
    }

# Initialize the process id of the thread
# Get results of _run_CLONE_SKIP
# If it seems we're in the child process
#  If the fork failed
#   Print a detailed warning
#   Return undefined to indicate the failure

    my $pid;
    my $clone_skip = _run_CLONE_SKIP();
    unless ($pid = fork) {
        unless (defined( $pid )) {
            warnings::warnif("Thread creation failed: Could not fork child from pid $$, tid $TID: ".($! ? $! : ''));
            return undef;
        }

#  Set up the connection for handling queries
#  Set appropriate thread exit behavior
#  If thread context is defined
#   If context is list
#    Execute the routine that we're supposed to execute (list context)
#   Else
#    Execute the routine that we're supposed to execute (scalar context)
#  Else
#    Execute the routine that we're supposed to execute (void context)
#  Print warning if thread terminated abnormally (if not main thread)
#  Mark this thread as shutting down
#  Save the result
#  And exit the process

        _init_thread($clone_skip, $thread_context, undef, $stack_size);
        if (defined($thread_exit) && $thread_exit eq EXIT_THREAD_ONLY) {
            threads->set_thread_exit_only(1);
        } elsif (defined($thread_exit) && $thread_exit eq EXIT_THREADS_ONLY) {
            _command( '_set_threads_exit_only',1 );
        }
        my @result;
        my $error;
        if (defined $thread_context) {
            if ($thread_context) {
                eval { @result = $sub->( @_ ); };
            } else {
                eval { $result[0] = $sub->( @_ ); };
            }
        } else {
            eval { $sub->( @_ ); };
        }
#warn "$TID: context = ".(defined $thread_context ? $thread_context ? 'array' : 'scalar' : 'void').",result (".scalar(@result).")=".CORE::join(',',@result); #TODO: for debugging only
        if ($@) {
            $error = $@;
            warn "Thread $TID terminated abnormally: $@"
                if $TID && warnings::enabled();
        }
        $SHUTTING_DOWN = 1;
        _command( '_tojoin',$error,@result );
        CORE::exit();
    }

# Mark PID for reaping, if using custom CHLD signal handler
# Obtain the thread id from the thread just started
# Create an object for it and return it

    $CHILD_PID{$pid} = undef;
    my ($tid) = _command( '_waitppid2ctid',$$ );
    $class->_object( $tid,$pid );
} #new

#---------------------------------------------------------------------------

sub isthread {

# Die now if this process is already marked as a thread
# Set up stuff so this process is now a detached thread
# Mark this thread as a detached thread (and run clone skip, even though we're not in parent)

    _croak( "Process $$ already registered as a thread" )
     if exists( $ISATHREAD{$$} );
    _init_thread( _run_CLONE_SKIP(), undef, 1 );
} #isthread

#---------------------------------------------------------------------------
#  IN: 1 class (ignored)
#      2 new value of debug flag (optional)
# OUT: 1 current value of debug flag

sub debug { $DEBUG = $_[1] if @_ > 1; $DEBUG } #debug

#---------------------------------------------------------------------------
#  IN: 1 class or instantiated object
# OUT: 1 thread id

sub tid {

# Obtain the object
# Return the thread local tid if called as a class method
# Return the field in the object, or fetch and set and return that

    my $self = shift;
    return $TID unless ref($self);
    $self->{'tid'} ||= _command( '_pid2tid',$self->{'pid'} );
} #tid

#---------------------------------------------------------------------------
#  IN: 1 class (ignored)
# OUT: 1 instantiated object

sub self { shift->_object( $TID,$$ ) } #self

#---------------------------------------------------------------------------
#  IN: 1 class (ignored)
#      2 thread id
# OUT: 1 instantiated object or undef if no thread by that tid or detached

sub object {

# Obtain the parameters
# If there is a defined thread id (and tid is not main thread)
#  Obtain the associated process id
#  Return blessed object if we actually got a process id
# Indicate we couldn't make an object

    my ($class,$tid) = @_;
    if (defined($tid) && $tid != 0) {
        return if $tid == 0;
        my $pid = _command( '_tid2pid',$tid );
        return $class->_object( $tid,$pid ) if defined( $pid );
    }
    undef;
} #object

#---------------------------------------------------------------------------
#  IN: 1 class
#  IN: 2 (optional) boolean value indicating type of list desired
# OUT: 1..N instantiated objects

sub list {

# Obtain the class
# Obtain the hash with process ID's keyed to thread ID's
# Initialize list of objects
# For all of the threads, ordered by ID
#  Add instantiated object for this thread
# Return the list of instantiated objects, or num of objects in scalar context

    my $class = shift;
    my %hash = _command( '_list_tid_pid', @_ );
    my @object;
    foreach (sort {$a <=> $b} keys %hash) {
        push( @object,$class->_object( $_,$hash{$_} ) );
    }
    wantarray ? @object : scalar @object;
} #list

#---------------------------------------------------------------------------

sub yield { sleep 0.001; } #yield

#---------------------------------------------------------------------------
#  IN: 1 class or instantiated object
# OUT: 1..N state of the indicated thread

sub is_detached { _command( '_is_detached',shift->tid ) } #is_detached

#---------------------------------------------------------------------------
#  IN: 1 class or instantiated object
# OUT: the memory location of the internal thread structure
# Note: this won't guarantee reusable address, as it's dynamically generated

sub _handle {

# Obtain the class or object
# If is an object, return address of object
# Otherwise, return address of class

    my $self = shift;
    return refaddr( $self->_object( $self->tid,$self->{'pid'} ) )
        if ref($self);
    return refaddr( $self->_object( $self->tid,$$ ) );

} #_handle

#---------------------------------------------------------------------------
#  IN: 1 class or instantiated object
# OUT: the thread (process) stack size

sub get_stack_size {

# Obtain the class or object
# Return the current size

    my $self = shift;
    return _command( '_get_set_stack_size',ref($self) ? $self->tid : undef );
} #get_stack_size

#---------------------------------------------------------------------------
#  IN: 1 class or instantiated object
#      2 new default stack size
# OUT: the old default thread (process) stack size

sub set_stack_size { shift; return _command( '_get_set_stack_size',undef,shift() ) } #set_stack_size

#---------------------------------------------------------------------------
#  IN: 1 class
#  IN: 2 exit status

sub exit {
    shift;
    defined $_[0] ? CORE::exit($_[0]) : CORE::exit();
} #exit

#---------------------------------------------------------------------------

# instance methods

#---------------------------------------------------------------------------
#  IN: 1 instantiated object
#  IN: 2 boolean value
# OUT: 1..N error result (if any) of the indicated thread

sub set_thread_exit_only {
    _command( '_set_thread_exit_only',shift->tid,shift );
} #set_thread_exit_only

#---------------------------------------------------------------------------
#  IN: 1 class or instantiated object
# OUT: 1..N state of the indicated thread

sub wantarray {

# Obtain the class or object
# If is an object, return thread context of specified thread
# Otherwise, return thread context of current thread

    my $self = shift;
    return _command( '_wantarray',$self->tid ) if ref($self);
    return $THREAD_CONTEXT;
} #wantarray

#---------------------------------------------------------------------------
#  IN: 1 instantiated object
# OUT: 1..N results of the indicated thread

sub detach {

# Obrain the result
# Die if an error occured
# Otherwise, return true

    my ($success, $errtxt) = _command( '_detach',shift->tid );
    Carp::croak($errtxt) unless $success;
    return 1;
} #detach

#---------------------------------------------------------------------------
#  IN: 1 instantiated object
# OUT: 1..N results of the indicated thread

sub join {

# Obrain the result
# Die if an error occured
# Otherwise, return joined result (returned by joined thread) in appropriate context

    my ($success, @result) = _command( '_join',shift->tid );
    Carp::croak(@result) unless $success;
    return defined CORE::wantarray ? CORE::wantarray ? @result : $result[-1] : ();
} #join

#---------------------------------------------------------------------------
#  IN: 1 instantiated object
# OUT: 1..N error result (if any) of the indicated thread

sub error { _command( '_error',shift->tid ) } #error

#---------------------------------------------------------------------------
#  IN: 1 instantiated threads object
#      2 other instantiated threads object
# OUT: 1 whether they refer to the same thread

sub equal { $_[0]->tid == $_[1]->tid } #equal

#---------------------------------------------------------------------------
#  IN: 1 instantiated threads object
#      2 other instantiated threads object
# OUT: 1 whether they refer to the same thread

sub nequal { $_[0]->tid != $_[1]->tid } #nequal

#---------------------------------------------------------------------------
#  IN: 1 instantiated threads object
# OUT: 1 tid of the object

sub stringify { $_[0]->tid } #stringify

#---------------------------------------------------------------------------
#  IN: 1 instantiated object
# OUT: 1 state of the indicated thread

sub is_running { _command( '_is_running',shift->tid ) } #is_running

#---------------------------------------------------------------------------
#  IN: 1 instantiated object
# OUT: 1 state of the indicated thread

sub is_joinable { _command( '_is_joinable',shift->tid ) } #is_joinable

#---------------------------------------------------------------------------
#  IN: 1 instantiated object
# OUT: 1 state of the indicated thread

sub is_deadlocked { _command( '_is_deadlocked',shift->tid ) } #is_deadlocked

#---------------------------------------------------------------------------
#  IN: 1 instantiated object
#      2 signal number or name to send
# OUT: 1 thread object

sub kill {

# Get the object
# Get the signal
# Die if incorrect usage
# Return immediately if no signal defined
# Die unless signal is valid
# Send signal
# Return thread object

    my $self = shift;
    my $signal = shift;
    Carp::croak("Usage: \$thr->kill('SIG...')") unless blessed($self);
    return $self unless defined $signal;
    Carp::croak("Unrecognized signal name or number: $signal")
        unless grep(/^$signal$/,
            map('SIG'.$_, split(/\s+/, $Config::Config{sig_name})),
            split(/\s+/, $Config::Config{sig_name}),
            split(/\s+/, $Config::Config{sig_num}));
    _command( '_kill',$self->tid,$signal );
    $self;
} #kill

#---------------------------------------------------------------------------

# exportables

#---------------------------------------------------------------------------
#  IN: 1 subroutine reference of sub to start execution with
#      2..N any parameters to be passed
# OUT: 1 instantiated object

sub async (&;@) {
    if (defined CORE::wantarray) {
        if (CORE::wantarray) {
            my @result = new( 'threads',@_ );
        } else {
            my $result = new( 'threads',@_ );
        }
    } else {
        new( 'threads',@_ );
    }
} #async

#---------------------------------------------------------------------------

# standard Perl features

#---------------------------------------------------------------------------
# Default reaper, if using custom CHLD signal handler (prevents thread zombies)

sub REAPER {

# Localize system error and status variables
# Toggle flag indicating that reaper was called, if user hasn't defined a CHLD handler
# For just child thread processes, loop and reap
#  If we are main thread, exit if shared process exited and main thread running

    local $!; local $?;
    $IFNDEF_REAPER_CALLED = 1 unless forks::signals->is_sig_user_defined('CHLD');
    while (my $pid = each %CHILD_PID) {
        my $waitpid = waitpid($pid, WNOHANG);
        if (defined($waitpid) && $waitpid == $pid && (WIFEXITED($?) || WIFSIGNALED($?))) {
            delete( $CHILD_PID{$pid} );
            if ($$ == $PID_MAIN_THREAD) {
                CORE::exit() if $waitpid == $SHARED && !$MAIN_EXIT_WITH_ABRT;
            }
        }
    }
} #REAPER

#---------------------------------------------------------------------------
# Shared server reaper

sub REAPER_SHARED_DAEMON {

# Localize system error and status variables
# While we have zombie processes, loop and reap
#  Store exit value if process was main thread and exit value not already set
#  Immediately exit shared server

    local $!; local $?;
    while ((my $pid = waitpid(-1, WNOHANG)) > 0) {
        if ($pid == $PID_MAIN_THREAD && (WIFEXITED($?) || WIFSIGNALED($?))) {
            $EXIT_VALUE = ($? >> 8) & 0xFF unless defined($EXIT_VALUE);
            $RUNNING = 0;
        }
    }
} #REAPER_SHARED_DAEMON

#---------------------------------------------------------------------------
# Special ABRT signal handler for main thread

sub _sigtrap_handler_main_abrt {

# Revert to system default CHLD handler (most portable exit behavior)
# Just reutrn if ABRT already handled, or if main thread is shutting down
# Mark main thread as exiting due to ABRT from shared process
# Exit immediately

    $forks::signals::sig->{CHLD} = 'DEFAULT';
    return if $MAIN_ABRT_HANDLED++ || $SHUTTING_DOWN || $SHUTTING_DOWN_END;
    $MAIN_EXIT_WITH_ABRT = 1;
    CORE::exit();
} #_sigtrap_handler_main_abrt

#---------------------------------------------------------------------------
# Default sigtrap handler

sub _sigtrap_handler_defined {

# Obtain the signal sent
# If valid signal and this is a valid thread
#  If not main thread and currently not exchanging with server
#   Add signal to deferred list unless it is already in the list
#   Return immediately with false (void) value
# Return with true value

    my ($sig) = @_;
    if ($sig && exists($ISATHREAD{$$}) && defined($PID) && $$ == $PID) {
        if ($threads::SEND_IN_PROGRESS
                || ($threads::RECV_IN_PROGRESS && length($threads::RECV_DATA) > 0)) {
            push @DEFERRED_SIGNAL, $sig unless grep(/^$sig$/, @DEFERRED_SIGNAL);
            return;
        }
    }
    return 1;
}

sub _sigtrap_handler_undefined {

# Call defined thread sig handler routine (to handle deferred signal logic, if required)
# If valid signal and this is a valid thread (not main thread)
#  Print a general warning
# Mark this thread as shutting down (for quiet exit)
# Exit

    my ($sig) = @_;
    return unless _sigtrap_handler_defined(@_);
    if ($sig && exists($ISATHREAD{$$}) && defined($PID) && $$ == $PID && $TID) {
        print STDERR "Signal SIG$sig received, but no signal handler set"
            ." for thread $TID\n"
            if warnings::enabled('threads');
    }
    $SHUTTING_DOWN = 1;
    CORE::exit();
} #_sigtrap_handler_undefined

#---------------------------------------------------------------------------
# Shared variable server sigtrap handler

sub _sigtrap_handler_shared {

# Obtain the signal sent
# Propegate signal to main thread

    my ($sig) = @_;
    CORE::kill($sig, $PID_MAIN_THREAD);
} #_sigtrap_handler_shared

#---------------------------------------------------------------------------
# Default module initializaton handler

sub _init {

# Return if module already initialized

    return if $HANDLED_INIT;

_log( " ! global startup" ) if DEBUG;

# Create a server that can only take one connection at a time or die now
# Find out the port we're running on and save that for later usage
# Make sure that the server is non-blocking

    if ($THREADS_UNIX) {
        _croak( "UNIX socket file '$THREADS_UNIX$$' in use by non-socket file" )
            if -e $THREADS_UNIX.$$ && !-S $THREADS_UNIX.$$;
        _croak( "Unable to delete UNIX socket file '$THREADS_UNIX$$'" )
            if -S $THREADS_UNIX.$$ && !unlink($THREADS_UNIX.$$);
        $QUERY = IO::Socket::UNIX->new(
         Local  => $THREADS_UNIX.$$,
         Listen => SOMAXCONN,
        ) or _croak( "Couldn't start the listening server: $@" );
        chmod 0777, $THREADS_UNIX.$$;
        $PORT = $THREADS_UNIX.$$;
    } else {
        $QUERY = IO::Socket::INET->new(
         LocalAddr => '127.0.0.1',
         Listen    => SOMAXCONN,
        ) or _croak( "Couldn't start the listening server: $@" );
        $PORT = $QUERY->sockport;
    }
    _nonblock( $QUERY );

# Perform the fork
# Die if the fork really failed

    my $forkpid = fork;
    _croak( "Could not start initial fork" ) unless defined( $forkpid );

# If shared server should be child process of main thread
#  If we are in the parent (main thread)
#   Do stuff
#  Else (we are in the child (shared server))
#   Do stuff
# Else
#  If we are in the parent (shared server)
#   Do stuff
#  Else (we are in the child (main thread))
#   Do stuff

    if ($THREADS_INTEGRATED_MODEL) {
        if ($forkpid) {
            $PID_MAIN_THREAD = $$;
            $SHARED = $forkpid;
            _init_main(1);
        } else {
            $PID_MAIN_THREAD = getppid();
            $SHARED = $$;
            _server_pre_startup();
            _init_server();
        }
    } else {
        if ($forkpid) {
            $PID_MAIN_THREAD = $forkpid;
            $SHARED = $$;
            _server_pre_startup();
            _init_server(1);
        } else {
            $PID_MAIN_THREAD = $$;
            $SHARED = getppid();
            _init_main();
        }
    }

# Mark forks initialization as complete

    $HANDLED_INIT = 1;
} #_init

#---------------------------------------------------------------------------
# Default main thread initialization handler

sub _init_main {
    my $is_parent = shift;

# Use forks::signal to overload %SIG for safest forks-aware signal behavior

# TODO: consider this case as a less-invasive signal handling system, for
#       cases where users wish to have fully overloadable signals via %SIG
#    foreach (@TRAPPED_SIGNAL) {
#        import sigtrap 'handler', (defined($SIG{$_})
#            ? \&_sigtrap_handler_defined
#            : \&_sigtrap_handler_undefined), $_;
#    }
#    import sigtrap ('handler', \&_sigtrap_handler_main_abrt, 'ABRT');
#    import sigtrap ('handler', ($FORCE_SIGCHLD_IGNORE ? 'IGNORE' : \&REAPER), 'CHLD');
    import forks::signals
        ifndef => {
            %THR_UNDEFINED_SIG,
            ABRT => \&_sigtrap_handler_main_abrt,
            CHLD => $FORCE_SIGCHLD_IGNORE ? 'IGNORE' : [\&REAPER, SA_NOCLDSTOP | SA_RESTART]
        },
        ifdef => {
            %THR_DEFINED_SIG,
            ABRT => \&_sigtrap_handler_main_abrt,
            CHLD => $FORCE_SIGCHLD_IGNORE ? 'IGNORE' : \&REAPER
        };

# Make this thread 0

    _init_thread(_run_CLONE_SKIP());
} #_init_main

#---------------------------------------------------------------------------
# Default thread server initializaton handler

sub _init_server {
    my $is_parent = shift;

# Reset all signal handlers to default
# If is parent
#  Configure signal handlers
#  Configure child signal handler
# Prevent server taking over TTY on exit when in debugger
# Start handling requests as the server

    delete( @SIG{keys %SIG} );
    if ($is_parent) {
        import sigtrap ('handler', \&_sigtrap_handler_shared,
            qw(normal-signals USR1 USR2 die error-signals));
        $SIG{CHLD} = \&REAPER_SHARED_DAEMON;
    }

    $DB::inhibit_exit = 0;
    &_server;
} #_init_server

#---------------------------------------------------------------------------
#  IN: 1 class (ignored)
#      2..N subroutines to export (default: async only)

sub import {

# Obtain the class

    my $self = shift;

# Overload string context of thread object to return TID, if requested

    if ((my $idx = List::MoreUtils::firstidx(
        sub { $_ eq 'stringify' }, @_)) >= 0) {
        import overload '""' => \&stringify;
        splice(@_, $idx, 1);
    }

# Initialize module thread server process, if required

    _init();

# Set exit context of threads, if requested

    if ((my $idx = List::MoreUtils::firstidx(
        sub { $_ eq 'exit' }, @_)) >= 0) {
        my @args = splice(@_, $idx, 2);
        if ($args[1] eq EXIT_THREADS_ONLY) {
            _command( '_set_threads_exit_only',1 );
        } elsif ($args[1] eq EXIT_THREAD_ONLY) {
            threads->set_thread_exit_only(1);
        }
    }

# Set thread stack size, if requested

    if ((my $idx = List::MoreUtils::firstidx(
        sub { $_ eq 'stack_size' }, @_)) >= 0) {
        my @args = splice(@_, $idx, 2);
        _command( '_get_set_stack_size',undef,$ITHREADS_STACK_SIZE || $args[1] );
    }

# Perform the export needed

    _export( scalar(caller()),@_ );        
} #import

BEGIN {

# forks::shared and threads::shared share same import method

    *forks::import = *forks::import = \&import;
} #_BEGIN

# Functions to allow external modules an API hook to specific runtime states

sub _server_pre_startup {}
sub _server_post_startup {}
sub _end_server_pre_shutdown {}
sub _end_server_post_shutdown {}

#---------------------------------------------------------------------------

my $END_CALLED;
sub _END {

# Revert to default CHLD handler to insure portable, reliable shutdown
# Prevent ths subroutine from ever being called twice
# Localize $! and $? to prevent accidental override during shutdown
# If this process is the shared server
#  Calculate and report stats on running and/or unjoined threads (excluding main thread)
#  Forcefully terminate any lingering thread processes (except main thread)
#  Forcefully terminate main thread (allowing END block to perform cleanup)
#  Shutdown the socket server
#  Delete UNIX socket file if the socket file exists
#  Allow external modules opportunity to clean up thread process group resources
# If this process is a valid thread (including main thread if $THREADS_INTEGRATED_MODEL)
#  Mark this thread as shutting down
#  Reset CORE::GLOBAL::exit to default
#  Indicate that this process has been shut down to the server (if appropriate)
#  Mark this thread as shut down (so we won't send or receive anymore)
#  If this is main thread using non-daemon model
#   Wait a bit for shared process to exit (or hard kill if it doesn't respond)
#   Synchronize thread exit status with shared process (as required)
# Alter exit status, if required

    $forks::signals::sig->{CHLD} = 'DEFAULT';
    LOCALEXITBLOCK: {
        last if $END_CALLED;
        $END_CALLED = 1;
        local $!; local $?;
        if (!exists( $ISATHREAD{$$} ) && defined($SHARED) && $$ == $SHARED) {
            my $running_and_unjoined = 0;
            my $finished_and_unjoined = 0;
            my $running_and_detached = 0;
            foreach my $tid (grep(!/^0$/, keys %TID2PID)) {
                if ($DETACHED !~ m/\b$tid\b/) {
                    $running_and_unjoined++
                        if !exists $RESULT{$tid} && exists $NOTJOINED{$tid};
                    $finished_and_unjoined++ if exists $RESULT{$tid};
                }
            }
            foreach (grep(!/^0$/, keys %DETACHED_NOTDONE)) {
                $running_and_detached++;
            }

            print STDERR "Perl exited with active threads:\n"
                ."\t$running_and_unjoined running and unjoined\n"
                ."\t$finished_and_unjoined finished and unjoined\n"
                ."\t$running_and_detached running and detached\n"
                if ($running_and_unjoined 
                    || $finished_and_unjoined || $running_and_detached);

            my @pidtokill;
            while (my ($tid, $client) = each %TID2CLIENT) {
                eval {
                    my $written = send( $client,'',0 );
                    if (defined( $written )) {
                        push @pidtokill, $TID2PID{$tid}
                            if $tid && defined $TID2PID{$tid}
                                && CORE::kill(0, $TID2PID{$tid});
                    };
                };
            }
            CORE::kill('SIGKILL', $_) foreach @pidtokill;
            CORE::kill('SIGABRT', $PID_MAIN_THREAD)
                if !$MAIN_EXIT_NO_ABRT && CORE::kill(0, $PID_MAIN_THREAD);

            $QUERY->shutdown(2) if defined $QUERY;
            unlink($PORT) if $THREADS_UNIX && -S $PORT;

            _end_server_post_shutdown();
        } elsif (exists( $ISATHREAD{$$} ) && defined($PID) && $$ == $PID && ($THREADS_INTEGRATED_MODEL || $TID)) {
            $SHUTTING_DOWN_END = 1;
            {
                no warnings 'redefine';
                *CORE::GLOBAL::exit = $old_core_global_exit;
            }
            _command( '_shutdown',$TID )
                if CORE::kill(0, $SHARED) && ($TID > 0 || !$MAIN_ABRT_HANDLED);
            $SHUTDOWN = 1;

            if ($THREADS_INTEGRATED_MODEL && $TID == 0) {
                local $!;
                local $SIG{ALRM} = sub { die };
                alarm(3);
                eval { waitpid($SHARED, 0); alarm(0); };
                if ($@) {
                    CORE::kill('SIGHUP', $SHARED) if CORE::kill(0, $SHARED);   #TODO: do we really need to be this agressive?
                } else {
                    $EXIT_VALUE = ($? >> 8) & 0xFF if $MAIN_EXIT_WITH_ABRT;
                }
            }
        }
    }
    $? = $EXIT_VALUE if defined $EXIT_VALUE && !$END_CALLED;
} #_END

#---------------------------------------------------------------------------

sub _CHECK {

# Call end block routine
# Exit with non-zero value if shared server, to prevent multiple compile check reports

    _END();
    CORE::exit(1)
        if (!exists( $ISATHREAD{$$} ) && defined($SHARED) && $$ == $SHARED);
} #_CHECK

#---------------------------------------------------------------------------

# internal subroutines server-side

#---------------------------------------------------------------------------

sub _server {

# Set nice value if environment variable set and if we're running as root
# Mark the parent thread id as detached

    { my $oldfh = select(STDOUT); $| = 1; select($oldfh); }
    POSIX::nice( $SERVER_NICE ) if $SERVER_NICE && !$<;
    $DETACHED = $NEXTTID;

# Create the select object in which all the connections are stored
# Initialize the length of message to be received hash
# Initialize the received message hash
# Initialize the var to hold current time (for time calculations each loop)

    my $select = IO::Select->new( $QUERY );
    my %toread;
    my %read;
    my $curtime;
    
# Localize Storable variables to allow CODE refs, if using Storable >= 2.05

    local $Storable::Deparse = 1 if $Storable::VERSION >= 2.05;
    local $Storable::Eval = 1 if $Storable::VERSION >= 2.05;

# Initialize the number of polls
# While we're running in the main dispatch loop
#  Update timedwaiting index
#  Get current time
#  Load next event timedwaiting expiration time (if any)
#  Wait until there is something to do or a cond_timedwaiting event has expired
#  Get current time
#  Increment number of polls
#  Handle any timedwaiting events that may have expired

    my $polls = 0;
    _server_post_startup();
    while ($RUNNING || %DONEWITH) {
if (DEBUG) {
 my $clients = keys %WRITE;
 _log( " ! $clients>>" ) if $clients;
}
        keys %WRITE if RESET_EACH_ITER;
        my $write = (each %WRITE) || '';
        _update_timedwaiting_idx();
        $curtime = time();
        my ($sleep_min) = $write ? (.001) : List::MoreUtils::minmax(
            @TIMEDWAITING_IDX ? $TIMEDWAITING_IDX[0]->[2] - $curtime : $MAX_POLL_SLEEP,
            $DEADLOCK_DETECT_TS_NEXT ? $DEADLOCK_DETECT_TS_NEXT - $curtime : $MAX_POLL_SLEEP,
            $BLOCKING_JOIN_CHECK_TS_NEXT ? $BLOCKING_JOIN_CHECK_TS_NEXT - $curtime : $MAX_POLL_SLEEP        
        );
_log( " ! max sleep time = $sleep_min" ) if DEBUG;
        my @reading = $select->can_read( $sleep_min > 0 ? $sleep_min : 0.001 );
        $curtime = time();
_log( " ! <<".@reading ) if DEBUG and @reading;
        $polls++;
        _handle_timedwaiting();
        
#  For all of the clients that have stuff to read
#   If we're done with this client, ignore further input until socket closed
#   If this is a new client
#    Accept the connection
#    If using INET sockets
#     Check if client is in the allow list
#      Immediately close client socket if not in allow list
#      And reloop
#    Make sure the client is non-blocking

        foreach my $client (@reading) {
            next if exists( $DONEWITH{$client} );
            if ($client == $QUERY) {
                $client = $QUERY->accept();
                unless ($THREADS_UNIX) {
                    if ($INET_IP_MASK ne '' && $client->peerhost() !~ m/$INET_IP_MASK/) {
                        warn 'Thread server rejected connection: '
                            .$client->peerhost().':'.$client->peerport().' does not match allowed IP mask'."\n";
                        close( $client );
                        next;
                    }
                }
                _nonblock( $client );

#    Save refs to real client object keyed to thread id and stringified object
#    Make sure the reverse lookup will work
#    Add the client to the list of sockets that we can select on
#    Send the thread ID to the client and increment (now issued) thread ID
#    And reloop

_log( " ! adding thread $NEXTTID" ) if DEBUG;
                $TID2CLIENT{$NEXTTID} = $client;
                $CLIENT2TID{$client} = $NEXTTID;
                $select->add( $client );
                $WRITE{$client} = _pack_response( ['_set_tid',$NEXTTID++] );
                next;
            }

#   Initialize the number of bytes to be read per block
#   If we haven't received the length of the message yet
#    Obtain the length, reloop if no length yet
#    Reduce first read to exactly match block size

            my $size = $BUFSIZ;
            unless ($toread{$client}) {
                next unless $toread{$client} = _length( $client );
#_log( " <$CLIENT2TID{$client} $toread{$client} length" ) if DEBUG;
                $size -= MSG_LENGTH_LEN;
            }

#   Initialize scalar to receive data in
#   If something went wrong with reading
#    Die (we can't have this going about now can we)
#     unless call would block or was interrupted by signal
#   Add the data to the request read for this client if anything was read

            my $data;
            unless (defined( recv($client,$data,$size,0) ) and length($data)) {
                _croak( "Error ".($! ? $! + 0 : '')." reading from $CLIENT2TID{$client}: ".($! ? $! : '') )
                    unless ($! == EWOULDBLOCK || $! == EAGAIN || $! == EINTR);
            }
_log( " <$CLIENT2TID{$client} ".length($data)." of $toread{$client}" ) if DEBUG;
            $read{$client} .= $data if defined($data);
        }

#  For all of the clients for which we have read stuff
#   If we have read something already
#    If we have all we're expecting

        keys %read if RESET_EACH_ITER;
        while (my $client = each %read) {
            if (my $read = length( $read{$client} )) {
                if ($read == $toread{$client}) {
_log( " =$CLIENT2TID{$client} ".CORE::join(' ',(_unpack_request( $read{$client} ) || '')) ) if DEBUG;

#     Create untainted version of what we got
#     Go handle that
#     Remove the number of characters to read
#    Elseif we got too much
#     Die now

                    $read{$client} =~ m#^(.*)$#s;
                    _handle_request( $client,$1 );
                    delete( $toread{$client} );
                    delete( $read{$client} );
                } elsif ($read > $toread{$client}) {
                    _croak( "Got $read bytes, expected only $toread{$client} from $CLIENT2TID{$client}: ".CORE::join( ' ',_unpack_request( $read{$client} ) ) );
                }
            }
        }

#  While there is a client to which we can write
#   Verify that there still is data to be written (may have changed after read)
#   Try to write whatever there was to write
#   If write was successful
#    If number of bytes written exactly same as what was supposed to be written
#     Just remove everything that was supposed to be removed
#    Elsif we've written some but not all because of blocking
#     Remove what was written, still left for next time
#    Else (something seriously wrong)
#     Die now
#   Else (something seriously wrong)
#    Die now
#   Fetch the next client to write to

        while ($write) {
            unless (defined $WRITE{$write}) {
                delete( $WRITE{$write} );
                $write = each %WRITE;
                next;
            }
            my $written =
             send( $TID2CLIENT{$CLIENT2TID{$write}},$WRITE{$write},0 );
_log( " >$CLIENT2TID{$write} $written of ".length($WRITE{$write}) ) if DEBUG;
            if (defined( $written )) {
                if ($written == length( $WRITE{$write} )) {
                    delete( $WRITE{$write} );
                } else {
                    substr( $WRITE{$write},0,$written ) = '';
                }
            } elsif ($! == EWOULDBLOCK || $! == EAGAIN || $! == EINTR) {
                #defer writing this time around
            } elsif ($! == ECONNRESET && $CLIENT2TID{$write} == 0) {
                #main thread exited: wait for SIGCHLD
                delete( $WRITE{$write} );
                next;
            } else {
                _croak( "Error ".($! ? $! + 0 : '').": Could not write ".(length $WRITE{$write})
                    ." bytes to $CLIENT2TID{$write}: ".($! ? $! : '') );
            }
            $write = each %WRITE;
        }
my $error = [$select->has_exception( .1 )] if DEBUG;
if (DEBUG) { _log( " #$CLIENT2TID{$_} error" ) foreach @$error; }

#  If asynchronous deadlock detection enabled and next event time has expired

        if ($DEADLOCK_DETECT && $DEADLOCK_DETECT_PERIOD && $curtime >= $DEADLOCK_DETECT_TS_NEXT) {
            _detect_deadlock_all();
            $DEADLOCK_DETECT_TS_NEXT = $curtime + $DEADLOCK_DETECT_PERIOD;
        }

#  If deadlock resolution is enabled and there are deadlocked threads
#   Get only one thread from each pair of deadlocked threads
#   Schedule signal for each pid to terminate to resolve deadlock
#   Clear deadlocked thread list

        if ($DEADLOCK_RESOLVE && %DEADLOCKED) {
            my @tid_to_kill;
            while (my $tid = each %DEADLOCKED) {
                push @tid_to_kill, $tid
                    if defined $DEADLOCKED{$DEADLOCKED{$tid}}
                        && $tid == $DEADLOCKED{$DEADLOCKED{$tid}};
                delete $DEADLOCKED{$tid};
            }
            foreach my $tid (@tid_to_kill) {
                print STDERR "Deadlock resolution: Terminating thread"
                    ." $tid (PID $TID2PID{$tid}) with signal $DEADLOCK_RESOLVE_SIG\n"
                    if warnings::enabled();
                $TOSIGNAL{$tid} = $DEADLOCK_RESOLVE_SIG;
            }
            %DEADLOCKED = ();
        }

#  For all of the clients that we need to send signals to
#   Make sure we won't check this client again
#   Skip this client if it's already terminated
#   Send requested signal to appropriate thread
#   If signal was SIGKILL, manually handle clean up
#   (note: this assumes any other signal would result in process safe exit)

        while (my ($tid, $signal) = each %TOSIGNAL) {
            delete( $TOSIGNAL{$tid} );
            next unless defined $TID2CLIENT{$tid};
            my $success = _signal_thread($tid, $signal);
            CORE::kill('SIGKILL', $TID2PID{$tid})
                unless $success;
_log( "sent $TID2PID{$tid} signal ".abs($signal) ) if DEBUG;
            _cleanup_unsafe_thread_exit($tid)
                if !$success || $signal eq 'KILL' || $signal eq 'SIGKILL'
                    || ($signal =~ m/^\d+$/ && $signal == SIGKILL);
        }

# If next check time has expired
#  For all of the clients that are currently blocking on threads
#   Check that process is still alive; otherwise, cleanup dead thread
#    If that did not clear the waiting thread
#     Output a warning (from server)
#     Notify the thread with undef (should really be an error)
#  Also check that main thread is still alive
        if ($curtime >= $BLOCKING_JOIN_CHECK_TS_NEXT) {
            while (my $tid = each %BLOCKING_JOIN) {
                unless (CORE::kill(0, $TID2PID{$tid})) {
                    _cleanup_unsafe_thread_exit($tid);
                    if (exists $BLOCKING_JOIN{$tid}) {
                        warn "BLOCKING_JOIN manually cleared for tid #$tid";
                        $WRITE{$TID2CLIENT{$tid}} = $undef;
                    }
                }
            }
            $BLOCKING_JOIN_CHECK_TS_NEXT = $curtime + $BLOCKING_JOIN_CHECK_PERIOD;
            $RUNNING = 0 unless CORE::kill(0, $PID_MAIN_THREAD);
        }

#  For all of the clients that we're done with
#   Reloop if there is still stuff to send there
#   Make sure we won't check this client again

        keys %DONEWITH if RESET_EACH_ITER;
        while (my $client = each %DONEWITH) {
            next if $RUNNING && exists( $WRITE{$client} );
_log( " !$CLIENT2TID{$client} shutting down" ) if DEBUG;
            delete( $DONEWITH{$client} );

#   Obtain the thread id
#   Obtain the client object (rather than its stringification)
#   Remove the client from polling loop
#   Properly close the client from this end
#   If we were waiting for this client to exit
#    Mark that main thread should not be ABRT signalled, if main thread is shutting down
#    Mark server to shutdown

            my $tid = $CLIENT2TID{$client};
            $client = $TID2CLIENT{$tid};
            $select->remove( $client );
            close( $client );
            if ($RUNNING eq $client) {
                $MAIN_EXIT_NO_ABRT = 1 if $tid == 0;
                $RUNNING = 0;
            }

#   Do the clean up

            my $pid = $TID2PID{$tid};
            delete( $TID2CLIENT{$tid} );
            delete( $CLIENT2TID{$client} );
            delete( $PID2TID{$pid} ) if defined $pid;
            if ($DETACHED =~ m/\b$tid\b/ or !exists( $NOTJOINED{$tid} )) {
                delete( $TID2PID{$tid} );
                delete( $TID2STACKSIZE{$tid} );
                delete( $TID2CONTEXT{$tid} );
            }
        }
    }

# Allow external modules opportunity to clean up thread process group resources
# Exit now, we're in the shared process and we've been told to exit

_log( " ! global exit: did $polls polls" ) if DEBUG;
    _end_server_pre_shutdown();
    defined $EXIT_VALUE ? CORE::exit($EXIT_VALUE) : CORE::exit();
} #_server

#---------------------------------------------------------------------------
#  IN: 1 tid to cleanup
#      2 (optional) error text to report

sub _cleanup_unsafe_thread_exit {

# Get tid of thread to cleanup
# Get error text to display in stack trace

    my $tid = shift;
    my $errtxt = shift || '';
    Carp::cluck( "Performing cleanup for dead thread $tid: $errtxt" )
        if warnings::enabled() && $errtxt ne '';   #TODO: disable these conditions?

# If thread isn't already joined and shutdown
#  Mark this thread as shutdown
#  Delete any messages that might have been pending for this client

    if (defined $TID2CLIENT{$tid}) {
        _shutdown($TID2CLIENT{$tid}, $tid);
        delete( $WRITE{$TID2CLIENT{$tid}} );
    }
} #_cleanup_unsafe_thread_exit

#---------------------------------------------------------------------------

sub _update_timedwaiting_idx {

#  If timedwaiting index expired flag set
#   Translate timedwaiting hash to sorted (index) array of all events
#   Reset index expired flag

    if ($TIMEDWAITING_IDX_EXPIRED) {
        @TIMEDWAITING_IDX = ();
        if (keys %TIMEDWAITING) {
            push @TIMEDWAITING_IDX, map($_, sort {$a->[2] <=> $b->[2]} map(@{$TIMEDWAITING{$_}}, keys %TIMEDWAITING));
        }
        $TIMEDWAITING_IDX_EXPIRED = 0;
    }
} #_update_timedwaiting_idx

#---------------------------------------------------------------------------

sub _handle_timedwaiting {
    
#  For all timed wait events
#   Obtain the tid, time, and ordinal event
#   If this timed event is expired and a timed event exists for this ordinal
#    Parse all timed events
#     If current event in list of timed events is the matching event to what has expired
#      Get the tid and target lock ordinal of the event
#      Delete event from list & expire timed event index
#      If ordinal is currently locked
#       Signal this variable for when the target locked variable is unlocked later
#      Else (ordinal not locked)
#       Assign lock to this tid
#       Immediately notify blocking thread that it should continue
#   Else last loop: minimize index parsing, as when current event isn't expired, remaining (ordered) events in array aren't either

    foreach (@TIMEDWAITING_IDX) {
        my (undef, $ordinal, $time, undef, $id) = @{$_};
        if ($time <= time() && defined $TIMEDWAITING{$ordinal} && ref($TIMEDWAITING{$ordinal}) eq 'ARRAY' && @{$TIMEDWAITING{$ordinal}}) {
            my @tw_events = @{$TIMEDWAITING{$ordinal}};
            for (my $i = 0; $i < scalar @tw_events; $i++) {
                if ($tw_events[$i]->[4] == $id) {
                    my ($tid, $l_ordinal) = @{splice(@{$TIMEDWAITING{$ordinal}}, $i, 1)}[0,3];
                    delete $TIMEDWAITING{$ordinal} unless @{$TIMEDWAITING{$ordinal}};
                    $TIMEDWAITING_IDX_EXPIRED = 1;
                    if (defined $LOCKED[$l_ordinal]) {
                        push @{$TIMEDWAITING_EXPIRED[$ordinal]}, [$tid, $l_ordinal];
                    } else {
                        $LOCKED[$l_ordinal] = $tid;
                        $WRITE{$TID2CLIENT{$tid}} = $false;
                    }
                    last;
                }
            }
        } else { 
            last;
        }
    }
} #_handle_timedwaiting

#---------------------------------------------------------------------------
#  IN: 1 socket to put into nonblocking mode

sub _nonblock { # not sure whether needed, this is really cargo-culting

# Obtain the socket in question
# Obtain the current flags
# Set the non-blocking flag onto the current flags

    my $socket = shift;
    my $flags = fcntl( $socket, F_GETFL, 0 )
     or _croak( "Error ".($! ? $! + 0 : '').": Can't get flags for socket: ".($! ? $! : '') );
    fcntl( $socket, F_SETFL, $flags | O_NONBLOCK )
     or _croak( "Error ".($! ? $! + 0 : '').": Can't make socket nonblocking: ".($! ? $! : '') );
} #_nonblock

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      3 flag whether to automatically detect deadlocks
#      2 detection period, in seconds
#      3 flag whether to resolve deadlock conflicts

sub _set_deadlock_option {

# Obtain client
# Set deadlock detection flag and period
# If period was changed
#  Set deadlock detection period (stored as a positive number)
#  Set next deadlock detection event,
# Set deadlock resolution flag
# If deadlock resolver is enabled, immediately do global deadlock detection
# Make sure the client knows the result

    my $client = shift;
    $DEADLOCK_DETECT = shift @_ ? 1 : $DEADLOCK_DETECT;
    my $period = shift @_;
    if (defined $period) {
        $DEADLOCK_DETECT_PERIOD = abs($period) + 0;
        $DEADLOCK_DETECT_TS_NEXT = time() + $DEADLOCK_DETECT_PERIOD;
    }
    $DEADLOCK_RESOLVE = shift @_ ? 1 : $DEADLOCK_RESOLVE;
    my $signal = shift @_;
    $DEADLOCK_RESOLVE_SIG = abs($signal) if $signal;
    _detect_deadlock_all() if $DEADLOCK_RESOLVE;
    $WRITE{$client} = $true;
} #_set_deadlock_option

#---------------------------------------------------------------------------
#  IN: 1 TID of thread waiting to lock
#      2 Ordinal of variable TID is waiting to lock
# OUT: 1 True or false, indicating whether or not deadlock was detected
#      2 TID of thread deadlocked with input TID
#      3 Ordinal of other variable involved in deadlock that is locked by output TID

sub _detect_deadlock {

# Obtain thread TID (1) and ordinal that it wants to lock
# Verify that that the ordinal is already locked (and not by the thread to analyze)
#  Get TID (2) of current ordinal locker
#  Get ordinal that TID (2) is currently blocking on
#  If TID (2) is blocking on TID (1) locked variable
#   Warn of the deadlock
#   Mark thread pair as deadlocked
#   Return true result
# Return false (no deadlock detected)

    my ($tid1, $tid1_locking_ordinal) = @_;
    if (defined $LOCKED[$tid1_locking_ordinal] && $LOCKED[$tid1_locking_ordinal] != $tid1) {
        my $tid2 = $LOCKED[$tid1_locking_ordinal];
        my $tid2_locking_ordinal = List::MoreUtils::firstidx(
            sub { ref($_) eq 'ARRAY' ? grep(/^$tid2$/, @{$_}) : 0 }, @LOCKING);
        if ($tid2_locking_ordinal != -1 && defined $LOCKED[$tid2_locking_ordinal]) {
            print STDERR "Deadlock detected:\n"
                .sprintf("% 7s% 12s% 13s   %s\n",'TID','SV LOCKED','SV LOCKING','Caller')
                .sprintf("% 7d% 12d% 13d   %s\n", $tid1, $tid2_locking_ordinal,
                    $tid1_locking_ordinal, CORE::join(' at line ', @{$TID2LOCKCALLER{$tid1}}[1..2]))
                .sprintf("% 7d% 12d% 13d   %s\n", $tid2, $tid1_locking_ordinal,
                    $tid2_locking_ordinal, CORE::join(' at line ', @{$TID2LOCKCALLER{$tid2}}[1..2]))
                if warnings::enabled();
            $DEADLOCKED{$tid1} = $tid2;
            $DEADLOCKED{$tid2} = $tid1;
            return CORE::wantarray ? (1, $tid2, $tid2_locking_ordinal) : 1;
        }
    }
    return 0;
} #_detect_deadlock

#---------------------------------------------------------------------------
# OUT: 1 Total number of deadlock (in terms of thread pairs) detected
#      2 Num of unique deadlock pairs detected

sub _detect_deadlock_all {

# Initialize counter
# For each ordinal in @LOCKING
#  If any threads are waiting to lock this ordinal
#   Increment deadlock counter foreach deadlock (unless thread is marked deadlocked)
# Return count of deadlocked pairs

    my $num_deadlocks = 0;
    for (my $ord = 0; $ord <= scalar @LOCKING; $ord++) {
        if (defined $LOCKING[$ord] && ref($LOCKING[$ord]) eq 'ARRAY') {
            foreach my $tid (@{$LOCKING[$ord]}) {
                $num_deadlocks += _detect_deadlock($tid, $ord)
                    unless exists $DEADLOCKED{$tid};
            }
         }
    }
    return $num_deadlocks;
} #_detect_deadlock_all

#---------------------------------------------------------------------------
#  IN: 1 TID of thread to signal
#      2 Signal to send (ID, name, or SIGname)

sub _signal_thread {

# Obtain the TID to signal
# Obtail the signal to send
# Determine the signal name or ID
# Send the signal

    my $tid = shift;
    my $signal = shift;
    my $mysig = uc($signal);

    $mysig = $1 if $mysig =~ m/^SIG(\w+)/;
    my $sigidx = List::MoreUtils::firstidx( sub { $_ eq $mysig },
        split(/\s+/, $Config::Config{sig_name}));
    my $signum = $sigidx == -1
        ? $signal : (split(/\s+/, $Config::Config{sig_name}))[$sigidx];
    
    if (CORE::kill(0, $TID2PID{$tid})) {
        return CORE::kill($signal, $TID2PID{$tid});
    } else {
        return 0;
    }
} #_signal_thread

#---------------------------------------------------------------------------

# internal subroutines client-side

#---------------------------------------------------------------------------
#  IN: 1 namespace to export to
#      2..N subroutines to export

sub _export {

# Obtain the namespace
# If we're supposed to debug the server also
#  Set debug flag
#  Lose the parameter

    my $namespace = shift().'::';
    if (defined( $_[0] ) and $_[0] eq 'debug') {
        $DEBUG = 1;
        shift;
    }

# Set the defaults if nothing specified
# Allow for evil stuff
# Export whatever needs to be exported

    @_ = qw(async) unless @_;
    no strict 'refs';
    *{$namespace.$_} = \&$_ foreach @_;
} #_export

#---------------------------------------------------------------------------
#  IN: 1 flag: whether to mark the thread as detached

sub _init_thread {

# Get results of _run_CLONE_SKIP from parent
# Get return context of thread
# Get flag whether this thread should start detached or not
# Get stack size for this thread
# Mark this process as a thread
# Reset thread local tid value (so the process doesn't have its parent's tid)
# Reset thread local pid value (so the process doesn't have its parent's pid)
# Store the return context of this thread

    my $clone_skip = shift;
    my $thread_context = shift;
    my $is_detached = shift;
    my $stack_size = shift;
    $ISATHREAD{$$} = undef;
    undef( $TID );
    undef( $PID );
    $THREAD_CONTEXT = $thread_context;

# Attempt to create a connection to the server or die

    if ($THREADS_UNIX) {
        $QUERY = IO::Socket::UNIX->new(
         Peer => $PORT,
        ) or _croak( "Couldn't connect to query server: $@" );
    } else {
        $QUERY = IO::Socket::INET->new(
         PeerAddr => '127.0.0.1',
         PeerPort => $PORT,
        ) or _croak( "Couldn't connect to query server: $@" );
    }

# Obtain the initial message from the query server
# Die now if it is the wrong type of message
# Set the tid
# Set the pid
# Disable debug on process exit if this isn't main thread
# Send the command to register the pid (unless starting detached or is main thread)
# Execute all of the CLONE subroutines if not in the base thread

    my @param = _receive( $QUERY );
    _croak( "Received '$param[0]' unexpectedly" ) if $param[0] ne '_set_tid';
    $TID = $param[1];
    $PID = $$;
    $DB::inhibit_exit = 0 if $TID;
    _send( $QUERY,'_register_pid',$TID,$$,($is_detached || !$TID ? undef : getppid()),$thread_context,$is_detached,$stack_size );
    _run_CLONE($clone_skip) if $TID;
    
# Wait for result of registration, die if failed
# If this is not main thread
#  Use forks::signal to overload %SIG for safest forks-aware signal behavior

    _croak( "Could not register pid $$ as tid $TID" ) unless _receive( $QUERY );
    if ($TID > 0) {
        import forks::signals
            ifndef => {
                %THR_UNDEFINED_SIG,
                CHLD => $FORCE_SIGCHLD_IGNORE ? 'IGNORE' : [\&REAPER, SA_NOCLDSTOP | SA_RESTART]
            },
            ifdef => {
                %THR_DEFINED_SIG,
                CHLD => $FORCE_SIGCHLD_IGNORE ? 'IGNORE' : \&REAPER
            };
    }

# Reinitialize random number generator (as we're simulating new interpreter creation)
# Overload global exit to conform to ithreads API (exits all threads).

    srand;
    {
        no warnings 'redefine';
        *CORE::GLOBAL::exit = sub {
            threads::_command( '_toexit',$_[0] );
            defined $_[0] ? CORE::exit($_[0]) : CORE::exit();
        };
    }

    return 1;
} #_init_thread

#---------------------------------------------------------------------------

# internal subroutines, both server-side as well as client-side

#---------------------------------------------------------------------------
#  IN: 1 arrayref of parameters to be put in message
#  IN: 2 command filter type (request or response)
#  IN: 3 command name
# OUT: 1 formatted message (MSG_LENGTH_LEN bytes packed length + CMD_TYPE_INTERNAL + data)

sub _pack {
    my $data_aref = shift;
    my $cmd_fltr_type = shift;
    my $cmd_name = shift;
    my $cmd_num = $cmd_type_to_num{$cmd_name} if $cmd_name;
    my $is_default_pack_type = defined $cmd_fltr_type && defined $cmd_num ? 0 : 1;
    
# If using default pack type
#  Freeze the parameters that have been passed
# Else
#  Pack data using custom filter
    
    my $data;
    if ($is_default_pack_type) {
        $data = pack('C', CMD_TYPE_DEFAULT).Storable::freeze( $data_aref );
    } else {
        my $filter = $cmd_num_to_filter[$cmd_num]->[$cmd_fltr_type]->[CMD_FLTR_ENCODE];
        $data = pack('C', CMD_TYPE_INTERNAL).pack('S', $cmd_num).$filter->($data_aref);
    }

# Calculate the length, pack it and return it with the frozen stuff

    pack( 'N',length( $data ) ).$data;
} #_pack_internal

#---------------------------------------------------------------------------
#  IN: 1 arrayref of parameters to be put in message
#  IN: 2 command name
# OUT: 1 formatted message

sub _pack_request { _pack(shift, CMD_FLTR_REQ, @_); } #_pack_request

#---------------------------------------------------------------------------
#  IN: 1 arrayref of parameters to be put in message
#  IN: 2 command name
# OUT: 1 formatted message

sub _pack_response { _pack(shift, CMD_FLTR_RESP, @_); } #_pack_response

#---------------------------------------------------------------------------
#  IN: 1 formatted message (without MSG_LENGTH_LEN byte length info)
#  IN: 2 command filter type (request or response)
# OUT: 1..N [msg name (if known), whatever was passed to "_pack"]

sub _unpack {

# Handle either default or custom filtered messages

    my $msg = shift;
    my $cmd_fltr_type = shift;
    my $type = unpack('C', substr($msg, CMD_TYPE_IDX, CMD_TYPE_LEN));
    if ($type == CMD_TYPE_DEFAULT) {
        return (undef, @{Storable::thaw( substr($msg, CMT_TYPE_FROZEN_CONTENT_IDX) )});
    } elsif ($type == CMD_TYPE_INTERNAL) {
        my $cmd_num = unpack('S', substr($msg, CMD_TYPE_INTERNAL_SUBNAME_IDX, CMD_TYPE_INTERNAL_SUBNAME_LEN));
        my $filter = $cmd_num_to_filter[$cmd_num]->[$cmd_fltr_type]->[CMD_FLTR_DECODE];
        return ($cmd_num_to_type[$cmd_num], $filter->(substr($msg, CMD_TYPE_INTERNAL_CONTENT_IDX)));
    } else {
        _croak ( "Unknown command type: $type" );
    }
} #_unpack

#---------------------------------------------------------------------------
#  IN: 1 formatted message (without MSG_LENGTH_LEN byte length info)
# OUT: 1..N [msg name (if known), whatever was passed to "_pack"]

sub _unpack_request { _unpack(shift, CMD_FLTR_REQ); } #_unpack_request

#---------------------------------------------------------------------------
#  IN: 1 formatted message (without MSG_LENGTH_LEN byte length info)
# OUT: 1..N [msg name (if known), whatever was passed to "_pack"]

sub _unpack_response { _unpack(shift, CMD_FLTR_RESP); } #_unpack_response

#---------------------------------------------------------------------------
#  IN: 1 client object
#      2 flag: don't croak if there is no length yet
# OUT: 1 length of message to be received

sub _length {

# Obtain client
# Initialize length variable
# While true
#  If we successfully read
#   Add length read to total
#   If we read successfully
#    If we got enough bytes for a length
#     Return the actual length
#    Elsif we didn't get anything
#     Return 0 if we don't need to croak yet
#     Break out of loop (no data found, where data was expected)
#    Decrease how much left there is to read by how much we just read
#  Elsif action would block or was interrupted by a signal
#   Sleep for a short time (i.e. don't hog CPU)
#  Else
#   Break out of loop (as some other error occured)

    my $client = shift;
    my $total_length = 0;
    my $todo = MSG_LENGTH_LEN;
    while ($total_length < MSG_LENGTH_LEN) {
        my $result = recv( $client,my $length,$todo,0 );
        if (defined( $result )) {
            $total_length += length( $length );
            if ($total_length == MSG_LENGTH_LEN) {
                return unpack( 'N',$length );
            } elsif ($total_length == 0) {
                return 0 if shift;
                last;
            }
            $todo -= length( $length );
        } elsif ($! == EWOULDBLOCK || $! == EAGAIN || $! == EINTR) {
            sleep 0.001;
        } else {
            last;
        }
    }

# If was ECONNABORTED (server abort) or ECONNRESET (client abort)
#  If is a thread
#   Warn and exit immediately (server connection terminated, 
#    likely due to main thread shutdown)
#  Else (is shared server)
#   Clear the error if this was main thread exiting
#   Cleanup "dead" thread
#   Report no data (length 0)
# Unless we're shutting down and we're not running in debug mode
#  Die, there was an error

    my $tid = defined $TID ? 'server' : $CLIENT2TID{$client};
    my $errtxt = "Error ".($! ? $! + 0 : '')
        .": Could not read length of message"
        .(defined $tid ? " from $tid" : '').": ".($! ? $! : '') if $!;
    if (!$! || $! == ECONNABORTED || $! == ECONNRESET) {
        if (exists( $ISATHREAD{$$} )) {
            $SHUTTING_DOWN = 1;
_log( "Thread $TID terminated abnormally: $errtxt" ) if DEBUG;
#warn "***_length: Thread $TID terminated abnormally: $errtxt";  #TODO: for debugging only
            CORE::exit();
        } else {
            $errtxt = undef if $CLIENT2TID{$client} == 0;
            _cleanup_unsafe_thread_exit($CLIENT2TID{$client}, $errtxt);
            return 0;
        }
    }
    _croak( $errtxt ) unless (($SHUTTING_DOWN || $SHUTTING_DOWN_END) && !DEBUG);
} #_length

#---------------------------------------------------------------------------
#  IN: 1 client object
#      2 frozen message to send

sub _send {

# Obtain the client object
# Create frozen version of the data
# Calculate the length of data to be sent

    my $client = shift;
    my $frozen = grep(/^$_[0]$/, @cmd_filtered) ? _pack_request( \@_, shift ) : _pack_request( \@_, $_[0] );
    my $length = length( $frozen );
_log( "> ".CORE::join(' ',map {$_ || ''} eval {_unpack_request( substr($frozen,MSG_LENGTH_LEN) )}) )
 if DEBUG;

# Localize and set thread data comm flag
# Loop while there is data to send
#  Send the data, find out how many really got sent
#  If data was sent
#   Remove sent data from string buffer
#   Increment total bytes sent
#  Elsif action would block or was interrupted by a signal
#   Sleep for a short time (i.e. don't hog CPU)
#  Else (an error occured)
#   If was ECONNABORTED (server abort) or ECONNRESET (client abort)
#    Warn and exit immediately (server connection terminated, likely due to main thread shutdown)
#   Die now unless shuttind down and not in debug mode
#   Return immediately

    $frozen =~ m#^(.*)$#s;
    my ($data, $total_sent) = ($1, 0);
    DEFERREDSIGBLOCK: {
        local $threads::SEND_IN_PROGRESS = 1;
        while ($total_sent < $length) {
            my $sent = send( $client,$data,0 );
            if (defined( $sent )) {
                substr($data, 0, $sent) = '';
                $total_sent += $sent;
            } elsif ($! == EWOULDBLOCK || $! == EAGAIN || $! == EINTR) {
                sleep 0.001;
            } else {
                my $errtxt = "Error ".($! ? $! + 0 : '')
                    ." when sending message to server: ".($! ? $! : '');
                if (!$! || $! == ECONNABORTED || $! == ECONNRESET) {
                    warn "Thread $TID terminated abnormally: $errtxt"
                        if warnings::enabled() && $TID
                            && !$SHUTTING_DOWN && !$SHUTTING_DOWN_END;
                    $SHUTTING_DOWN = 1;
#warn "===Thread $TID terminated abnormally: $errtxt";   #TODO: for debugging only
                    CORE::exit();
                }
                _croak( $errtxt )
                    unless (($SHUTTING_DOWN || $SHUTTING_DOWN_END) && !DEBUG);
                return;
            }
        }
    }

# Handle deferred signals
# Reset deferred signal list

    $SIG{$_}->($_) foreach (@DEFERRED_SIGNAL);
    @DEFERRED_SIGNAL = ();
} #_send

#---------------------------------------------------------------------------
#  IN: 1 client object
# OUT: 1..N parameters of message

sub _receive {

# Obtain the client object
# Localize and set thread comm flag
# Block signals, if using custom CHLD signal handler
# Obtain the length
# Initialize the data to be received

    my $client = shift;
    DEFERREDSIGBLOCK: {
        local $threads::RECV_IN_PROGRESS = 1;
        my $length = my $todo = _length( $client );
        my $frozen;

# While there is data to get
#  Get some data
#  If we got data
#   Add what we got this time
#   If we got it all
#    Untaint what we got
#    Obtain any parameters if possible
#    Remove method type from parameters
#    Return the result
#   Set up for next attempt to fetch
#  ElseIf call would block or was interrupted by signal
#   Sleep a bit (to not take all CPU time)

        while ($todo > 0) {
            local $threads::RECV_DATA = '';
            my $result = recv( $client,$threads::RECV_DATA,$todo,0 );
            if (defined $result) {
                $frozen .= $threads::RECV_DATA;
                if (length( $frozen ) == $length) {
                    $frozen =~ m#^(.*)$#s;
                    my @result = _unpack_response( $1 );
                    shift @result;
_log( "< @{[map {$_ || ''} @result]}" ) if DEBUG;
                    return CORE::wantarray ? @result : $result[0];
                }
                $todo -= length( $threads::RECV_DATA );
            } elsif ($! == EWOULDBLOCK || $! == EAGAIN || $! == EINTR) {
                sleep 0.001;
            } else {
                last;
            }
        }
    }

# Handle deferred signals
# Reset deferred signal list

    $SIG{$_}->($_) foreach (@DEFERRED_SIGNAL);
    @DEFERRED_SIGNAL = ();

# Unless we're shutting down and we're not running in debug mode
#  Die now (we didn't get the data)

    unless (($SHUTTING_DOWN || $SHUTTING_DOWN_END) && !DEBUG) {
        _croak( "Error ".($! ? $! + 0 : '').": Did not receive all bytes from $CLIENT2TID{$client}: ".($! ? $! : '') );
    }
} #_receive

#---------------------------------------------------------------------------

# all client-side handler internal subroutines from here on

#---------------------------------------------------------------------------
#  IN: 1 command to execute
#      2..N parameters to send
# OUT: 1 values returned by server

sub _command {

# Return now if this thread has shut down already or if server already shutdown
# Send the command + parameters
# Return immediately if main thread is shutting down in non-daemon mode
# Return the result

    return if (defined($PID) && $$ != $PID) || $SHUTDOWN
        || (($SHUTTING_DOWN || $SHUTTING_DOWN_END) && !$QUERY);
    _send( $QUERY,@_ );
    return if $$ == $PID_MAIN_THREAD
        && $SHUTTING_DOWN_END && $THREADS_INTEGRATED_MODEL;
    _receive( $QUERY );
} #_command

#---------------------------------------------------------------------------
#  IN: 1 class
#      2 thread id
#      3 process id
# OUT: 1 instantiated thread object

sub _object { bless {tid => $_[1], pid => $_[2]},ref($_[0]) || $_[0] } #_object

#---------------------------------------------------------------------------

# all server-side handler internal subroutines from here on

#---------------------------------------------------------------------------
#  IN: 1 instantiated socket
#      2 frozen data to be handled

sub _handle_request {

# Obtain the socket
# Get the command name and its parameters
# If this is CMD_TYPE_DEFAULT command, get sub from parameters
# Allow for variable references (sub name is not a ref)
# Execute the command, be sure to pass the socket

    my $client = shift;
    my ($sub,@param) = _unpack_request( shift );
    $sub = shift @param unless defined $sub;
    no strict 'refs';
    &{$sub}( $client,@param );
} #_handle_request

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 tid to register
#      3 pid to associate with the tid
#      4 flag: whether to mark thread as detached
# OUT: 1 whether successful (sent to client)

sub _register_pid {

# Obtain the parameters
# Initialize the status as error
# If we received a process id
#  If there is a client object for this thread
#   If this is the first time this thread is being registered
#    Register this thread
#    Make sure we can do a reverse lookup as well
#    Push tid on ppid2tid queue, if thread has a parent (e.g. not main thread)
#    If thread is marked as detached
#     Add to the list of detached threads
#     Store return context of thread
#    Else
#     Mark thread as joinable
#     Store the return context of the thread
#    Set status to indicate success

    my ($client,$tid,$pid,$ppid,$thread_context,$detach,$stack_size) = @_;
    my $status = 0;
    if ($pid) {
        if (defined $TID2CLIENT{$tid}) {
            unless (exists $PID2TID{$pid}) {
                $TID2PID{$tid} = $pid;
                $PID2TID{$pid} = $tid;
                $TID2STACKSIZE{$tid} = defined $stack_size ? $stack_size : $ITHREADS_STACK_SIZE;
                push @{$PPID2CTID_QUEUE{$ppid}}, $tid if $ppid;
                if ($detach) {
                    $DETACHED .= ",$tid";
                    $DETACHED_NOTDONE{$tid} = undef;
                } else {
                    $NOTJOINED{$tid} = undef;
                    $TID2CONTEXT{$tid} = $thread_context;
                }
                $status = 1;
            }
        }

#   If thread has a parent and there is a thread waiting for this ppid/ctid pair
#    Let that thread know
#    And forget that it was waiting for it

        if (defined $ppid && exists $BLOCKING_PPID2CTID_QUEUE{$ppid}) {
            _ppid2ctid_shift( $BLOCKING_PPID2CTID_QUEUE{$ppid},$ppid );
            delete( $BLOCKING_PPID2CTID_QUEUE{$ppid} );
        }
    }

# Let the client know how it went

    $WRITE{$client} = _pack_response( [$status] );
} #_register_pid

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 thread id to find associated process id of
# OUT: 1 associated process id

sub _tid2pid { $WRITE{$_[0]} = _pack_response( [$TID2PID{$_[1]}] ) } #_tid2pid

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 process id to find associated thread id of
# OUT: 1 associated thread id

sub _pid2tid { $WRITE{$_[0]} = _pack_response( [$PID2TID{$_[1]}] ) } #_pid2tid

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 process id of thread calling this method
# OUT: 1 associated thread id

sub _ppid2ctid_shift {
    $WRITE{$_[0]} = _pack_response( [shift @{$PPID2CTID_QUEUE{$_[1]}}] );
} #_ppid2ctid_shift

#---------------------------------------------------------------------------
#  IN: 1 client socket
#  IN: 2 (optional) boolean value indicating type of list desired
# OUT: 1..N tid/pid pairs of all threads

sub _list_tid_pid {

# Obtain the socket
# Initialize the parameters to be sent
# For all of the registered threads
#  Obtain the thread id
#  If user specified an argument to list()
#   If argument was a "true" value
#    (running) Reloop if it is detached or joined or no longer running (non-detached)
#    or a thread is already blocking to join it
#   Else
#    (joinable) Reloop if it is detached or joined or still running (non-detached)
#  Else
#   (all) Reloop if it is detached or joined or a thread is already blocking to join it
#  Add this tid and pid to the list
# Store the response

    my $client = shift;
    my @param;
    while (my($tid,$pid) = each %TID2PID) {
        if (@_) {
            if ($_[0]) {
                next if $DETACHED =~ m/\b$tid\b/ or !exists( $NOTJOINED{$tid} )
                    or exists( $RESULT{$tid} ) or exists( $BLOCKING_JOIN{$tid} );
            } else {
                next if $DETACHED =~ m/\b$tid\b/ or !exists( $NOTJOINED{$tid} )
                    or !exists( $RESULT{$tid} );
            }
        } else {
            next if $DETACHED =~ m/\b$tid\b/ or !exists( $NOTJOINED{$tid} )
                or exists( $BLOCKING_JOIN{$tid} );
        }
        push( @param,$tid,$pid );
    }
    $WRITE{$client} = _pack_response( [@param] );
} #_list_tid_pid

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 client process exit value
# OUT: 1 thread exit status

sub _toexit {

# Obtain the client object
# Unless thread exit should be localized to thread, main thread exited,
# or another thread performed global exit (waiting for it to shutdown)
#  Store exit value
#  Mark server process as ready to exit when this thread exits
# Make sure the client continues

    my $client = shift;
    my $exit_value = shift;
    unless ($CLIENT2TID{$client} == 0
            || defined ( $EXIT_VALUE ) || $THREADS_EXIT
            || exists( $THREAD_EXIT{$CLIENT2TID{$client}} )) {
        $EXIT_VALUE = $exit_value;
        $RUNNING = $client;
    }
    $WRITE{$client} = $true;
} #_toexit

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 thread id to which rule will apply
#      3 boolean state rule
# OUT: 1 thread exit status

sub _set_thread_exit_only {

# Obtain the client object
# Set the appropriate client thread exit method
# Make sure the client continues

    my $client = shift;
    my $tid = shift;
    my $thread_exit_only = shift @_ ? 1 : 0;
    if ($thread_exit_only) {
        $THREAD_EXIT{$tid} = undef;
    } else {
        delete( $THREAD_EXIT{$tid} );
    }
    $WRITE{$client} = $true;
} #_set_thread_exit_only

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 thread id calling this method
# OUT: 1 thread exit status

sub _set_threads_exit_only {

# Obtain the client object
# Set the global thread exit override state
# Make sure the client continues

    my $client = shift;
    $THREADS_EXIT = $_[0] ? 1 : 0;
    $WRITE{$client} = $true;
} #_set_threads_exit_only

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2..N result of thread
# OUT: 1 whether saving successful

sub _tojoin {

# Obtain the client object
# Obrain the client error (if any)
# Store the client error if there was an error
# If there is a thread id for this client, obtaining it on the fly
#  If there is a thread waiting for this result, obtaining client on the fly
#   Join the thread with this result
#  Elseif the thread was not detached
#   Save the result for later fetching
#  Elseif the thread was detached
#   Mark this detached thread as done
# Make sure the client knows the result

    my $client = shift;
    my $error = shift;
    $ERROR{$CLIENT2TID{$client}} = $error if defined $error;
    if (my $tid = $CLIENT2TID{$client}) {
        if (exists $BLOCKING_JOIN{$tid}) {
#warn "case 1: the result I got was ".scalar(@_).": ".CORE::join(',', @_);  #TODO: for debugging only
            _isjoined( $BLOCKING_JOIN{$tid},$tid,@_ );
        } elsif ($DETACHED !~ m/\b$tid\b/) {
            $RESULT{$tid} = \@_;
        } elsif ($DETACHED =~ m/\b$tid\b/) {
            delete( $DETACHED_NOTDONE{$tid} );
        }
    }
    $WRITE{$client} = $true;
} #_tojoin

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 thread id of thread to detach
# OUT: 1 whether first time detached

sub _detach {

# Obtain the parameters
# Set flag whether first time detached
# If another thread is already waiting to join this thread
#  Don't allow thread to become deached (return local thread exception)
# Else
#  Detach this thread
#  If target thread is still running
#   Mark it as detached and running
#  Else
#   Cleanup internal states (results) related to thread exit
# Let the client know the result

    my ($client,$tid) = @_;
    my $can_detach = $DETACHED !~ m/\b$tid\b/;
    my $errtxt = $can_detach ? '' : 'Thread already detached';
    if (exists $BLOCKING_JOIN{$tid} || ($can_detach && !exists( $NOTJOINED{$tid} ))) {
        $can_detach = 0;
        $errtxt = 'Cannot detach a joined thread';
#warn "Thread $CLIENT2TID{$client} attempted to detach a thread ($tid) pending join by another thread ($CLIENT2TID{$BLOCKING_JOIN{$tid}})"; #TODO: debugging
    }
    if ($can_detach) {
        $DETACHED .= ",$tid";
        if (defined $NOTJOINED{$tid}) {
            $DETACHED_NOTDONE{$tid} = undef;
        } else {
            delete( $RESULT{$tid} );
        }
        delete( $TID2CONTEXT{$tid} );
        delete( $TID2STACKSIZE{$tid} );
    }
    $WRITE{$client} = _pack_response( [$can_detach, $errtxt] );
} #_detach

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 process id to find associated thread id of

sub _waitppid2ctid {

# If there is already a thread id for this process id, set that
# Start waiting for the tid to arrive

    return &_ppid2ctid_shift if defined $PPID2CTID_QUEUE{$_[1]} && @{$PPID2CTID_QUEUE{$_[1]}};
    $BLOCKING_PPID2CTID_QUEUE{$_[1]} = $_[0];
} #_waitppid2ctid

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 thread id of thread to wait for result of

sub _join {

# If the thread is detached
#  Propagate error to thread
# ElseIf there is already a result for this thread
#  Mark the thread as joined and use the pre-saved result
# Elseif the results were fetched before
#  Propagate error to thread
# Elseif the thread terminated without join (i.e. terminated abnormally)
#  Return undef to thread
# Elseif thread process not running (i.e. thread death w/ no _shutdown)
#  Return undef to thread
# Elseif someone is already waiting to join this thread
#  Propagate error to thread
# Elseif thread is attempting to join on itself
#  Propagate error to thread
# Else
#  Start waiting for the result to arrive

    my ($client,$tid) = @_;
    if ($DETACHED =~ m/\b$tid\b/) {
#warn "Thread $CLIENT2TID{$client} attempted to join a detached thread: $tid";  #TODO: for debugging only
        $WRITE{$client} = _pack_response( [0, 'Cannot join a detached thread'] );
    } elsif (exists $RESULT{$tid}) {
#warn "case 2: $CLIENT2TID{$client} joining $tid immediately";  #TODO: for debugging only
        _isjoined( $client,$tid,@{$RESULT{$tid}} );
    } elsif (!exists( $NOTJOINED{$tid} )) {
#warn "Thread $CLIENT2TID{$client} attempted to join an already joined thread: $tid";   #TODO: for debugging only
        $WRITE{$client} = _pack_response( [0, 'Thread already joined'] );
    } elsif (!exists $TID2CLIENT{$tid}) {
#warn "case 4: $CLIENT2TID{$client} cannot join $tid";  #TODO: for debugging only
        $WRITE{$client} = _pack_response( [0, 'Cannot join a detached or already joined thread'] );
    } elsif (!exists( $TID2PID{$tid} ) || !CORE::kill(0, $TID2PID{$tid})) {
#warn "case 5: $CLIENT2TID{$client} cannot join $tid";  #TODO: for debugging only
        $WRITE{$client} = _pack_response( [0, 'Cannot join a detached or already joined thread'] );
    } elsif (defined $BLOCKING_JOIN{$tid}) {
#warn "Thread $CLIENT2TID{$client} attempted to join a thread already pending join: $tid";  #TODO: for debugging only
        $WRITE{$client} = _pack_response( [0, 'Thread already joined'] );
    } elsif ($CLIENT2TID{$client} == $tid) {
        $WRITE{$client} = _pack_response( [0, 'Cannot join self'] );
    } else {
#warn "case 6: $CLIENT2TID{$client} blocking on $tid";  #TODO: for debugging only
        $BLOCKING_JOIN{$tid} = $client;
    }
} #_join

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 thread id of thread to return result of

sub _error {

# Obtain the waiting client and the tid of which to check error status
# Write the current error state response

    my ($client,$tid) = @_;
    $WRITE{$client} = exists $ERROR{$tid}
        ? _pack_response( [$ERROR{$tid}] )
        : $undef;
} #error

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 thread id of thread, or not defined (if we want global stack size)
#      3 new default stack size (defined if this is a set operation)

sub _get_set_stack_size {

# Obtain client socket and TID
# Look up old stack size for this thread
# Set new stack size, if defined and is a valid integer
# Return old stack size

    my ($client,$tid,$size) = @_;
    my $old = defined $tid && exists $TID2STACKSIZE{$tid} ? $TID2STACKSIZE{$tid} : $ITHREADS_STACK_SIZE;
    $ITHREADS_STACK_SIZE = $size if defined $size && $size =~ m/^\d+$/o;
    $WRITE{$client} = _pack_response( [$old] );
} #_get_set_stack_size

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 thread id of thread to check state

sub _is_detached {

# Obtain client socket and TID
# Return boolean value to thread whether deatched or not

    my ($client,$tid) = @_;
    $WRITE{$client} = $DETACHED =~ m/\b$tid\b/ ? $true : $false;
} #_is_detached

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 thread id of thread to check state

sub _is_running {

# Obtain client socket and TID
# Return boolean value to thread whether running or not

    my ($client,$tid) = @_;
    $WRITE{$client} = ($DETACHED =~ m/\b$tid\b/ && exists $DETACHED_NOTDONE{$tid})
        || (defined $TID2PID{$tid} && !exists $RESULT{$tid} && exists $NOTJOINED{$tid})
        ? $true : $false;
} #_is_running

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 thread id of thread to check state

sub _is_joinable {

# Obtain client socket and TID
# Return boolean value to thread whether joinable or not

    my ($client,$tid) = @_;
    $WRITE{$client} = exists $RESULT{$tid} ? $true : $false;
} #_is_joinable

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 thread id of thread to check state

sub _is_deadlocked {

# Obtain client socket and TID
# Obtain ordinal of shared that TID is currently trying to lock (if any)
# If TID is not trying to lock anything
#  Return false to client
# Else
#  Check if thread is deadlocked and write appropriate value to client
# Return boolean value to thread whether deadlocked or not

    my ($client,$tid) = @_;
    my $ordinal = List::MoreUtils::firstidx(
        sub { ref($_) eq 'ARRAY' ? grep(/^$tid$/, @{$_}) : 0 }, @LOCKING);
    if ($ordinal == -1) {
        $WRITE{$client} = $false;
    } else {
        $WRITE{$client} = _detect_deadlock($tid, $ordinal) ? $true : $false;
    }
} #_is_deadlocked

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 thread id of thread to signal
#      3 (optional) signal to send

sub _kill {

# Obtain client socket, TID, and signal
# Mark the thread to be signaled with the specified signal
# Make sure the client continues

    my ($client,$tid,$signal) = @_;
    $TOSIGNAL{$tid} = $signal;
    $WRITE{$client} = $true;
} #_kill

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 thread id of thread to check state

sub _wantarray {

# Obtain client socket and TID
# Return thread context (true, defined, or undef)

    my ($client,$tid) = @_;
    $WRITE{$client} = defined $TID2CONTEXT{$tid} ? $TID2CONTEXT{$tid}
        ? $true : $defined : $undef;
} #_wantarray

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 reference to hash with parameters
#      3..N any extra values specified
# OUT: 1 tied ordinal number

sub _tie {

# Obtain client socket
# Obtain local copy of remote object
# Create the name of the routine to fake tying with here, in shared "thread"

    my $client = shift;
    my $remote = shift;
    my $tiewith = 'TIE'.uc($remote->{'type'});

# Obtain the module we should tie with
# If we could load that module successfully
#  Evaluate any code that needs to be evaluated
#  If there are module(s) to be used
#   If there is more than one
#    Use all of them
#   Else
#    Just use this one

    my $module = $remote->{'module'};
    if (eval "use $module; 1") {
        eval $remote->{'eval'} if defined( $remote->{'eval'} );
        if (my $use = $remote->{'use'} || '') {
            if (ref($use)) {
                eval "use $_" foreach @$use;
            } else {
                eval "use $use";
            }
        }

#  Obtain the ordinal number to be used for this shared variable
#  If successful in tieing it and save the object for this shared variable
#   Return the ordinal (we need that remotely to link with right one here)
# Return indicating error

        my $ordinal = $NEXTTIED++;
        if ($TIED[$ordinal] = $module->$tiewith( @_ )) {
            $WRITE{$client} = _pack_response( [$ordinal] );
            return;
        }
    }
    $WRITE{$client} = $undef;
} #_tie

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 ordinal number of variable
#      3 fully qualified name of subroutine to execute
#      4..N parameters to be passed
# OUT: 1..N parameters to be returned

sub _tied {

# Obtain the client socket
# Obtain the object to work with
# Obtain subroutine name to execute

    my $client = shift;
    my $object = $TIED[shift];
    my $sub = shift;

# Initialize code reference
# If there is a code reference already (fetch it on the fly)
# Elseif this is the first time we try this subroutine
#  Create a non-fully qualified version of the subroutine
#  Attempt to get a code reference for that and save it
# Call the subroutine if there is one and return the result

    my $code;
    if (exists $DISPATCH{$sub} && ($code = $DISPATCH{$sub})) {
    } elsif( !exists( $DISPATCH{$sub} ) ) {
    $sub =~ m#^(?:.*)::(.*?)$#;
        $code = $DISPATCH{$sub} = $object->can( $1 );
    }
    my @result;
    if ($code) {
        foreach ($code->( $object,@_ )) {
            if (my $ref = reftype($_)) {
                my $tied = $ref eq 'SCALAR' ? tied ${$_}
                    : $ref eq 'ARRAY' ? tied @{$_}
                    : $ref eq 'HASH' ? tied %{$_}
                    : $ref eq 'GLOB' ? tied *{$_}
                    : undef;
                if (defined $tied && blessed($tied) eq 'threads::shared') {
                    my $ref_obj = $TIED[$tied->{'ordinal'}];
                    bless($_, blessed(${$ref_obj})) if blessed(${$ref_obj});                    
                }
            }
            push @result, $_;
        }
    }
    $WRITE{$client} = $code ? _pack_response( \@result ) : $undef;
} #_tied

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 ordinal number of variable to bless
#      3 class type with which bless object
# OUT: 1 whether successful

sub _bless {

# Obtain the socket
# Obtain the ordinal number of the variable
# Set the tied object's blessed property

    my $client = shift;
    my $ordinal = shift;
    my $class = shift;
    bless(${$TIED[$ordinal]}, $class);

# Indicate that we're done to the client

    $WRITE{$client} = $true;
} #_bless

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 ordinal number of variable to analyze
# OUT: 1 refaddr of variables

sub _id {

# Obtain the socket
# Obtain the object to work with

    my $client = shift;
    my $object = $TIED[shift];

# Write response to client

    $WRITE{$client} = _pack_response( [refaddr( ${$object} )] );
} #_id

#---------------------------------------------------------------------------
#  IN: 1 client sockets
#      2 ordinal number of variable to remove
# OUT: 1 whether successful

sub _untie {

# Obtain the socket
# Obtain the ordinal number of the variable
# Obtain the object
# If we can destroy the object, obtaining code ref on the fly
#  Perform whatever needs to be done to destroy

    my $client = shift;
    my $ordinal = shift;
    my $object = $TIED[$ordinal];
    if (my $code = $object->can( 'DESTROY' )) {
        $code->( $object );
    }

# Kill all references to the variable
# Indicate that we're done to the client

    undef( $TIED[$ordinal] );
    $WRITE{$client} = $true;
} #_untie

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 ordinal number of variable to lock

sub _lock {

# Obtain the client socket
# Obtain the thread id of the thread
# Obtain the ordinal number of the shared variable
# Obtain the client caller filename and line

    my $client = shift;
    my $tid = $CLIENT2TID{$client};
    my $ordinal = shift;
    my $line = shift;
    my $filename = shift;

# If this shared variable is already locked, obtaining its tid on the fly
#  If it's the same thread id
#   Indicate a recursive lock for this variable
#   Let the client continue
#  Else
#   Add the thread to the list of ones that want to lock (and let it block)
#   Perform deadlock deadlock detection immediately, if appropriate

    if (defined $LOCKED[$ordinal]) {
        if ($tid == $LOCKED[$ordinal]) {
            $RECURSED[$ordinal]++;
            $WRITE{$client} = $undef;
        } else {
            push( @{$LOCKING[$ordinal]},$tid );
            $TID2LOCKCALLER{$tid} = [$ordinal, $filename, $line];
            _detect_deadlock($tid, $ordinal)
                if $DEADLOCK_DETECT && !$DEADLOCK_DETECT_PERIOD;
        }

# Else (this variable was not locked yet)
#  Lock this variable
#  Let the client continue

    } else {
        $LOCKED[$ordinal] = $tid;
        $TID2LOCKCALLER{$tid} = [$ordinal, $filename, $line];
        $WRITE{$client} = $undef;
    }
} #_lock

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 ordinal number of variable to unlock

sub _unlock {

# Obtain the client socket
# Obtain ordinal while checking whether locked
# Do the actual unlock
# Make sure the client continues

    my $client = shift;
    my $ordinal = _islocked( $client,shift );
    _unlock_ordinal( $ordinal ) if $ordinal;
    $WRITE{$client} = $true;
} #_unlock

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 ordinal number of (signal) variable to start waiting for
#      3 (optional) ordinal number of lock variable

sub _wait {

# If this is second form of cond_wait
#  Store ordinal of signal variable
#  Check if the lock variable is locked and return ordinal number and thread id
# Else
#  Check if the variable is locked and return ordinal number and thread id
#  Lock ordinal and ordinal are the same in this case; assign ordinal value to lock ordinal
# Unlock the variable
# Add this thread to the list of threads in cond_wait on this variable

    my ($ordinal,$tid,$l_ordinal);
    if (scalar @_ > 2) {
        $ordinal = $_[1];
        ($l_ordinal,$tid) = _islocked( @_[0,2],'cond_wait' );
    } else {
        ($ordinal,$tid) = _islocked( @_,'cond_wait' );
        $l_ordinal = $ordinal;
    }
    _unlock_ordinal( $l_ordinal );
    push( @{$WAITING[$ordinal]},[$tid, $l_ordinal] );
} #_wait

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 ordinal number of variable to start timed waiting for
#      3 absolute expiration time (epoch seconds) of timedwait event
#      4 (optional) ordinal number of lock variable

sub _timedwait {

# If this is second form of cond_wait
#  Store ordinal of signal variable
#  Check if the lock variable is locked and return ordinal number and thread id
# Else
#  Check if the variable is locked and return ordinal number and thread id
#  Lock ordinal and ordinal are the same in this case; assign ordinal value to lock ordinal
# Unlock the variable
# Add this thread to the list of threads in cond_timedwait on this variable

    my ($ordinal,$tid,$l_ordinal);
    my $time = splice(@_, 2, 1);
    if (scalar @_ > 2) {
        $ordinal = $_[1];
        ($l_ordinal,$tid) = _islocked( @_[0,2],'cond_timedwait' );
    } else {
        ($ordinal,$tid) = _islocked( @_,'cond_timedwait' );
        $l_ordinal = $ordinal;
    }
    _unlock_ordinal( $l_ordinal );
    push( @{$TIMEDWAITING{$ordinal}},[$tid, $ordinal, $time, $l_ordinal, ++$TIMEDWAITING_ID] );
    $TIMEDWAITING_IDX_EXPIRED = 1;
} #_timedwait

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 ordinal number of variable to signal one

sub _signal {

# Obtain local copy of the client
# Obtain ordinal

    my $client = shift;
    my $ordinal = shift;

# Get random number to determine which lock waiting list to use first
# Obtain the thread id, target lock ordinal from randomly chosen list
# Obtain the information from alternate list if there is no thread id yet

    my $rand = rand;
    my ($tid, $l_ordinal) = $rand > 0.5
        ? _signal_timedwaiting($ordinal) : _signal_waiting($ordinal);
    ($tid, $l_ordinal) = $rand > 0.5
        ? _signal_waiting($ordinal) : _signal_timedwaiting($ordinal)
        unless defined $tid;

# If a tid was found to be waiting
#  If the signal ordinal is the same as the lock ordinal or the variable they are waiting to relock is currently locked
#   Add the next thread id from the list of waiting or timed waiting threads (if any) to the head of the locking list
#  Else (lock var is not same as signal var and lock var is currently unlocked)
#   Assign lock to this tid
#   Immediately notify blocking thread that it should continue

    if (defined $tid) {
        if ($ordinal == $l_ordinal || defined $LOCKED[$l_ordinal]) {
            unshift( @{$LOCKING[$l_ordinal]}, $tid );
        } else {
            $LOCKED[$l_ordinal] = $tid;
            $WRITE{$TID2CLIENT{$tid}} = $true;
        }
    }

# Make sure the client continues

    $WRITE{$client} = $undef;
} #_signal

#---------------------------------------------------------------------------
#  IN: 1 ordinal number of variable to signal one
# OUT: 1 tid to signal
#      2 ordinal for thread to lock

sub _signal_waiting {

# Initialize the thread id and target lock ordinal
# If there exists a waiting event for this ordinal
#  Get the next thread id from the list of waiting threads (if any)

    my ($tid, $l_ordinal);
    if (defined $WAITING[$_[0]] && ref($WAITING[$_[0]]) eq 'ARRAY'
            && @{$WAITING[$_[0]]}) {
        ($tid, $l_ordinal) = @{shift(@{$WAITING[$_[0]]})};
    }
    return ($tid, $l_ordinal);
}

#---------------------------------------------------------------------------
#  IN: 1 ordinal number of variable to signal one
# OUT: 1 tid to signal
#      2 ordinal for thread to lock

sub _signal_timedwaiting {

# Initialize the thread id and target lock ordinal
# If there exists a timedwaiting event for this ordinal
#  Assign lock to this tid

    my ($tid, $l_ordinal);
    if (defined $TIMEDWAITING{$_[0]} && ref($TIMEDWAITING{$_[0]}) eq 'ARRAY'
            && @{$TIMEDWAITING{$_[0]}}) {
        ($tid, $l_ordinal) = @{shift(@{$TIMEDWAITING{$_[0]}})}[0,3];
        delete $TIMEDWAITING{$_[0]} unless @{$TIMEDWAITING{$_[0]}};
        $TIMEDWAITING_IDX_EXPIRED = 1;
    }
    return ($tid, $l_ordinal);
}

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 ordinal number of variable to signal all

sub _broadcast {

# Obtain local copy of the client
# Obtain ordinal
# If there are threads waiting or timed waiting
#  For all waiting or timed waiting threads
#   If the signal ordinal is the same as the lock ordinal or the variable they are waiting to relock is currently locked
#    Add it to the head of the locking list
#    Purge waiting list for this ordinal (as it's been transferred to locking list)
#    (Perl < 5.8 delete appears to sometimes corrupt array, so use undef in these cases)
#   Else (lock var is not same as signal var and lock var is currently unlocked)
#    Assign lock to this tid
#    Immediately notify blocking thread that it should continue
# Make sure the client continues

    my $client = shift;
    my $ordinal = shift;
    my ($tid, $l_ordinal);
    if (defined $WAITING[$ordinal] && ref($WAITING[$ordinal]) eq 'ARRAY' && @{$WAITING[$ordinal]}) {
        foreach (@{$WAITING[$ordinal]}) {
            ($tid, $l_ordinal) = @{$_};
            if ($ordinal == $l_ordinal || defined $LOCKED[$l_ordinal]) {
                unshift( @{$LOCKING[$l_ordinal]}, $tid );
            } else {
                $LOCKED[$l_ordinal] = $tid;
                $WRITE{$TID2CLIENT{$tid}} = $true;
            }
        }
        if ($] < 5.008) {
            $WAITING[$ordinal] = undef;
        } else {
            delete $WAITING[$ordinal];
        }
    }
    if (defined $TIMEDWAITING{$ordinal} && ref($TIMEDWAITING{$ordinal}) eq 'ARRAY' && @{$TIMEDWAITING{$ordinal}}) {
        foreach (@{$TIMEDWAITING{$ordinal}}) {
            ($tid, $l_ordinal) = @{$_}[0,3];
            if ($ordinal == $l_ordinal || defined $LOCKED[$l_ordinal]) {
                unshift( @{$LOCKING[$l_ordinal]}, $tid );
            } else {
                $LOCKED[$l_ordinal] = $tid;
                $WRITE{$TID2CLIENT{$tid}} = $true;
            }
            $TIMEDWAITING_IDX_EXPIRED = 1;
        }
        delete $TIMEDWAITING{$ordinal};
    }
    
    $WRITE{$client} = $undef;
} #_broadcast

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 thread id that was shutdown

sub _shutdown {

# Obtain the client socket
# Obtain the thread id
# If thread did not appear to exit cleanly
#  Simulate join of the thread with no result
# If it is not the main thread shutting down
#  Unlock all locked variables
#  Reset one of the following events (as thread can only be in one blocking state)
#   Try removing TID from @LOCKING
#   Try removing TID from @WAITING
#   Try removing TID from %TIMEDWAITING
#  Delete any messages that might have been pending for this client
# Else (it's the main thread shutting down and main thread is parent process)
#  Update running flag for pending server shutdown
# Mark this client for deletion
# Send result to thread to allow it to shut down

    my $client = shift;
    my $tid = shift;
    if ((exists $NOTJOINED{$tid} && !exists $RESULT{$tid})
        || ($DETACHED =~ m/\b$tid\b/ && exists $DETACHED_NOTDONE{$tid})) {
        _tojoin($client);   #TODO: report error here ($thr->error reportable)?
    }
    if ($tid) {
        while ((my $ordinal = List::MoreUtils::firstidx(
            sub { defined $_ ? $_ eq $tid : 0 }, @LOCKED)) >= 0) {
            $RECURSED[$ordinal] = 0;
            _unlock_ordinal($ordinal);
        }
        BLOCKING_EVENT: {
            if ((my $ordinal = List::MoreUtils::firstidx(
                sub { ref($_) eq 'ARRAY' ? grep(/^$tid$/, @{$_}) : 0 }, @LOCKING)) >= 0) {
                $LOCKING[$ordinal] = [grep(!/^$tid$/, @{$LOCKING[$ordinal]})];
                last BLOCKING_EVENT;
            }
            if ((my $ordinal = List::MoreUtils::firstidx(
                sub { ref($_) eq 'ARRAY' ? grep(/^$tid$/, @{$_}) : 0 }, @WAITING)) >= 0) {
                $WAITING[$ordinal] = [grep(!/^$tid$/, @{$WAITING[$ordinal]})];
                last BLOCKING_EVENT;
            }
            if ((my $ordinal = List::MoreUtils::firstidx(
                sub { $_->[0] == $tid }, @TIMEDWAITING_IDX)) >= 0) {
                if ((my $idx = List::MoreUtils::firstidx(sub { $_->[0] == $tid }, @{$TIMEDWAITING{$ordinal}})) >= 0) {
                    splice(@{$TIMEDWAITING{$ordinal}}, $idx, 1);
                    $TIMEDWAITING_IDX_EXPIRED = 1;
                    last BLOCKING_EVENT;
                }
            }
        }
    } elsif ($THREADS_INTEGRATED_MODEL) {
        $RUNNING = $client;
    }
    $DONEWITH{$client} = undef;
    $WRITE{$client} = $true;    #TODO: make sure socket is still alive, otherwise could cause server to croak on dead socket (need to protect server with correct error state--EPIPE?)
} #_shutdown

#---------------------------------------------------------------------------
#  IN: 1 ordinal number of shared variable to unlock

sub _unlock_ordinal {

# Obtain the ordinal number
# If this is a recursive lock
#  Remove one recursion
#  And return

    my $ordinal = shift;
    if ($RECURSED[$ordinal]) {
        $RECURSED[$ordinal]--;
        return;
    }

# Get random number to determine which lock waiting list to use first
# Obtain the thread id, target lock ordinal, response from randomly chosen list
# Obtain the information from alternate list if there is no thread id yet

    my $rand = rand;
    my ($tid, $l_ordinal, $response) = $rand > 0.5
        ? _unlock_ordinal_timedwaiting_expired($ordinal) : _unlock_ordinal_locking($ordinal);
    ($tid, $l_ordinal, $response) = $rand > 0.5
        ? _unlock_ordinal_locking($ordinal) : _unlock_ordinal_timedwaiting_expired($ordinal)
        unless defined $tid;

# If there is a thread id for the lock
#  Make that the thread locking the variable
#  And have that thread continue
# Else (still no thread wanting to lock)
#  Just reset the lock for this variable

    if (defined $tid){
        $LOCKED[$l_ordinal] = $tid;
        $WRITE{$TID2CLIENT{$tid}} = $response;
    } else {
        $LOCKED[$l_ordinal] = undef;
    }
} #_unlock_ordinal

#---------------------------------------------------------------------------
#  IN: 1 ordinal number of shared variable to unlock
# OUT: 1 tid to acquire ordinal lock
#      2 ordinal being locked
#      3 response for waiting thread

sub _unlock_ordinal_locking {

# Obtain thread id from locking list and return the results

    return (shift(@{$LOCKING[$_[0]]}), $_[0], $true);
}

#---------------------------------------------------------------------------
#  IN: 1 ordinal number of shared variable to unlock
# OUT: 1 tid to acquire ordinal lock
#      2 ordinal being locked
#      3 response for waiting thread

sub _unlock_ordinal_timedwaiting_expired {
    
# Initialize the thread id and target lock ordinal
# Initialize default response to true
# If there exist any timed waiting events that expired and are waiting to relock
#  Get the thread id and target lock ordinal
#  Set response to false (indicating this event timed out)
# Else
#  Assign default target lock ordinal
# Returns the results

    my ($tid, $l_ordinal);
    my $response = $true;
    if (ref($TIMEDWAITING_EXPIRED[$_[0]]) eq 'ARRAY' && @{$TIMEDWAITING_EXPIRED[$_[0]]}) {
        ($tid, $l_ordinal) = @{shift @{$TIMEDWAITING_EXPIRED[$_[0]]}};
        $response = $false;
    } else {
        $l_ordinal = $_[0];
    }
    return ($tid, $l_ordinal, $response);
}

#---------------------------------------------------------------------------
#  IN: 1 client socket
#      2 ordinal number of variable to start waiting for
#      3 function name to show when there is an error (undef: no error if wrong)
# OUT: 1 ordinal number of variable
#      2 thread id that keeps it locked

sub _islocked {

# Obtain the client socket
# Obtain the thread id of the thread
# Obtain the ordinal number of the shared variable
# If we're not the one locking
#  Return now with nothing if we don't want an error message
#  Die (we want an error message)
# Return the ordinal number and/or thread id

    my $client = shift;
    my $tid = $CLIENT2TID{$client};
    my $ordinal = shift;
    if (!defined $LOCKED[$ordinal] || $tid != $LOCKED[$ordinal]) {
        return unless $_[0];
        _croak( "You need a lock before you can $_[0]: variable #$ordinal ($tid != $LOCKED[$ordinal])" );
    }
    CORE::wantarray ? ($ordinal,$tid) : $ordinal;
} #_islocked

#---------------------------------------------------------------------------
#  IN: 1 client socket to which result will be sent
#      2 thread id of thread with result
#      3..N the result to be sent

sub _isjoined {

# Obtain the client
# Obtain the thread id

    my $client = shift;
    my $tid = shift;

# Unblock the client with the result
# Forget about that someone is waiting for this thread
# Forget about the result (if any)
# Forget about listing in ->list if this thread was shutdown already
# Mark that thread as joined
# Delete thread context information
# Delete thread stack size information

    $WRITE{$client} = _pack_response( [1, @_] );
#warn "case 7: tid $tid had this to say (".scalar(@_)."): ".CORE::join(',', @_);    #TODO: for debugging only
    delete( $BLOCKING_JOIN{$tid} );
    delete( $RESULT{$tid} );
    delete( $TID2PID{$tid} ) unless exists( $TID2CLIENT{$tid} );
    delete( $NOTJOINED{$tid} );
    delete( $TID2CONTEXT{$tid} );
    delete( $TID2STACKSIZE{$tid} );
} #_isjoined

#---------------------------------------------------------------------------

# debugging routines

#---------------------------------------------------------------------------
#  IN: 1 message to display

sub _croak { return &Carp::confess((defined $TID ? $TID : '')." ($$): ".shift) } #_croak

#---------------------------------------------------------------------------
#  IN: 1 message to log

sub _log {

# Obtain the message
# If it is a thread message
#  Obtain the thread id
#  Prefix thread id value
# Shorten message if _very_ long
# Log it

    my $message = shift;
    if (substr($message,0,1) ne ' ') {
        my $tid = defined($TID) ? $TID : '?';
        $message = "$tid $message";
    }
    $message = substr($message,0,256)."... (".(length $message)." bytes)"
     if length( $message ) > 256;
    print STDERR "$message\n";
}#_log

#---------------------------------------------------------------------------
#  IN: 1 client object
# OUT: 1 associated tid
#      2 associated pid

sub _client2tidpid {

# Obtain the thread id
# Return thread and process id

    my $tid = $CLIENT2TID{ (shift) };
    ($tid,$TID2PID{$tid});
} #_client2tidpid

#---------------------------------------------------------------------------

sub _run_CLONE_SKIP {

# Prepare hash for results
# For every package loaded (including main::)
#  Initialize code reference
#  If we tried to get the code reference before (may be undef if not found)
#   Use that

    my %result;
    $result{pkg} = ['main',
        grep { $_ !~ /^CORE::|::SUPER$/o } forks::Devel::Symdump->rnew->packages];
    foreach my $package (@{$result{pkg}}) {
        my $code;
        if (exists $CLONE_SKIP{$package}) {
            $code = $CLONE_SKIP{$package};

#  Else
#   Attempt to obtain the code reference, don't care if failed
#  Execute the CLONE_SKIP subroutine if found, and save result
# Return results

        } else {
            $code = $CLONE_SKIP{$package} = eval { $package->can( 'CLONE_SKIP' ) };
        }
        $result{skip}{$package} = $code->($package) if $code;
    }
    
    return \%result;
} #_run_CLONE_SKIP

#---------------------------------------------------------------------------

sub _run_CLONE {

# Load results of _run_CLONE_SKIP
# For every package loaded (including main::)
#  Initialize code reference
#  If this package CLONE_SKIP returned a true value
#   Find all blessed objects from this class
#    First, "damn" object to unbless and prevent DESTROY
#    Now replace value with an undef SCALAR ref, or undef the existing datastructure
#   Remove package from tracked entities
#   Immediately check next package (skip clone)
#  If we tried to get the code reference before (may be undef if not found)
#   Use that

    my $clone = shift || { skip => undef, pkg => ['main',
        grep { $_ !~ /^CORE::|::SUPER$/o } forks::Devel::Symdump->rnew->packages]};
    CLONE_LOOP: foreach my $package (@{$clone->{pkg}}) {
        my $code;
        if (exists( $clone->{skip}{$package} ) && $clone->{skip}{$package}) {
            $CLONE_SKIP_REF{$package} = {} unless $CLONE_SKIP_REF{$package};
            while (my ($addr, $ref) = each %{$CLONE_SKIP_REF{$package}}) {
                my $class = blessed(${$ref});
                if ($class && $class eq $package) {
                    Acme::Damn::damn(${$ref});
                    if (reftype( ${$CLONE_SKIP_REF{$package}{$addr}} ) eq 'HASH') {
                        undef %{${$CLONE_SKIP_REF{$package}{$addr}}};
                    } elsif (reftype( ${$CLONE_SKIP_REF{$package}{$addr}} ) eq 'ARRAY') {
                        undef @{${$CLONE_SKIP_REF{$package}{$addr}}};
                    } else {
                        undef ${${$CLONE_SKIP_REF{$package}{$addr}}};
                    }
                }
            }
            delete $CLONE_SKIP_REF{$package};
            next CLONE_LOOP;
        } elsif (exists $CLONE{$package}) {
            $code = $CLONE{$package};

#  Else
#   Attempt to obtain the code reference, don't care if failed
#  Execute the CLONE subroutine if found

        } else {
            $code = $CLONE{$package} = eval { $package->can( 'CLONE' ) };
        }
        $code->($package) if $code;
    }
} #_run_CLONE

#---------------------------------------------------------------------------

package
    forks::shared::_preload; # Preload forks::shared for seamless 'require threads::shared'

require forks::shared
 unless exists( $ENV{'THREADS_NO_PRELOAD_SHARED'} ) && $ENV{'THREADS_NO_PRELOAD_SHARED'};

#---------------------------------------------------------------------------

# Satisfy -require-

1;

__END__
=pod

=head1 NAME

forks - drop-in replacement for Perl threads using fork()

=head1 VERSION

This documentation describes version 0.34.

=head1 SYNOPSIS

  use forks;    #ALWAYS LOAD AS FIRST MODULE, if possible
  use warnings;

  my $thread = threads->new( sub {       # or ->create or async()
    print "Hello world from a thread\n";
  } );

  $thread->join;
  
  $thread = threads->new( { 'context' => 'list' }, sub {
    print "Thread is expected to return a list\n";
    return (1, 'abc', 5);
  }
  my @result = $thread->join();

  threads->detach;
  $thread->detach;

  my $tid    = $thread->tid;
  my $owntid = threads->tid;

  my $self    = threads->self;
  my $threadx = threads->object( $tidx );

  my @running = threads->list(threads::running);
  $_->join() foreach (threads->list(threads::joinable));
  $_->join foreach threads->list; #block until all threads done

  unless (fork) {
    threads->isthread; # could be used a child-init Apache handler
  }

  # Enable debugging
  use forks qw(debug);
  threads->debug( 1 );
  
  # Stringify thread objects
  use forks qw(stringify);
  
  # Check state of a thread
  my $thr = threads->new( ... );
  if ($thr->is_running()) {
    print "Thread $thr running\n"; #prints "Thread 1 running"
  }
  
  # Send a signal to a thread
  $thr->kill('SIGUSR1');

  # Manual deadlock detection
  if ($thr->is_deadlocked()) {
    print "Thread $thr is currently deadlocked!\n";
  }
  
  # Use forks as a drop-in replacement for an ithreads application
  perl -Mforks threadapplication
  
See L<threads/"SYNOPSIS"> for more examples.
  
=head1 DESCRIPTION

The "forks" pragma allows a developer to use threads without having to have
a threaded perl, or to even run 5.8.0 or higher.

Refer to the L<threads> module for ithreads API documentation.  Also, use

    perl -Mforks -e 'print $threads::VERSION'
    
to see what version of L<threads> you should refer to regarding supported API
features.

There were a number of goals that I am trying to reach with this implementation.

=over 2

Using this module B<only> makes sense if you run on a system that has an
implementation of the C<fork> function by the Operating System.  Windows
is currently the only known system on which Perl runs which does B<not>
have an implementation of C<fork>.  Therefore, it B<doesn't> make any
sense to use this module on a Windows system.  And therefore, a check is
made during installation barring you from installing on a Windows system.

=back

=head2 module load order: forks first

Since forks overrides core Perl functions, you are *strongly* encouraged to
load the forks module before any other Perl modules.  This will insure the
most consistent and stable system behavior.  This can be easily done without
affecting existing code, like:

    perl -Mforks  script.pl

=head2 memory usage

The standard Perl 5.8.0 threads implementation is B<very> memory consuming,
which makes it basically impossible to use in a production environment,
particularly with mod_perl and Apache.  Because of the use of the standard
Unix fork() capabilities, most operating systems will be able to use the
Copy-On-Write (COW) memory sharing capabilities (whereas with the standard Perl
5.8.0 threads implementation, this is thwarted by the Perl interpreter
cloning process that is used to create threads).  The memory savings have
been confirmed.

=head2 mod_perl / Apache

This threads implementation allows you to use a standard, pre-forking Apache
server and have the children act as threads (with the class method
L</"isthread">).

=head2 same API as threads

You should be able to run threaded applications unchanged by simply making
sure that the "forks" and "forks::shared" modules are loaded, e.g. by
specifying them on the command line.  Forks is currently API compatible with
CPAN L<threads> version C<1.53>.

Additionally, you do not need to worry about upgrading to the latest Perl
maintenance release to insure that the (CPAN) release of threads you wish to
use is fully compatibly and stable.  Forks code is completely independent of
the perl core, and thus will guarantee reliable behavior on any release of
Perl 5.8 or later.  (Note that there may be behavior variances if running
under Perl 5.6.x, as that version does not support safe signals and requires
a source filter to load forks).

=head2 using as a development tool

Because you do not need a threaded Perl to use forks.pm, you can start
prototyping threaded applications with the Perl executable that you are used
to.  Just download and install the "forks" package from CPAN.  So
the threshold for trying out threads in Perl has become much lower.  Even
Perl 5.005 should, in principle, be able to support the forks.pm module;
however, some issues with regards to the availability of XS features between
different versions of Perl, it seems that 5.6.0 (unthreaded) is what you need
at least.

Additionally, forks offers a full thread deadlock detection engine, to help
discover and optionally resolve locking issues in threaded applications.  See
L<forks::shared/"Deadlock detection and resolution"> for more information.

=head2 using in production environments

This package has successfully been proven as stable and reliable in production 
environments.  I have personally used it in high-availability, database-driven, 
message processing server applications since 2004 with great success.

Also, unlike pure ithreads, forks.pm is fully compatible with all perl modules,
whether or not they have been updated to be ithread safe.  This means that you
do not need to feel limited in what you can develop as a threaded perl
application, a problem that continues to plague the acceptance of ithreads in
production enviroments today.  Just handle these modules as you would when
using a standard fork: be sure to create new instances of, or connections to,
resources where a single instance can not be shared between multiple processes.

The only major concern is the potentially slow (relative to pure ithreads)
performance of shared data and locks.  If your application doesn't depend on
extensive semaphore use, and reads/writes from shared variables moderately
(such as using them primarily to deliver data to a child thread to process
and the child thread uses a shared structure to return the result), then this
will likely not be an issue for your application.  See the TODO section
regarding plans to tackle this issue.

Also, you may wish to try L<forks::BerkeleyDB>, which has shown signifigant
performance gains and consistent throughoutput in high-concurrency shared
variable applications.

=head2 Perl built without native ithreads

If your Perl release was not built with ithreads or does not support ithreads,
you will have a compile-time option of installing forks into the threads and
threads::shared namespaces.  This is done as a convenience to give users a
reasonably seamless ithreads API experience without having to rebuild their
distribution with native threading (and its slight performance overhead on all
perl runtime, even if not using threads).

B<Note:> When using forks in this manner (e.g. "use threads;") for the first
time in your code, forks will attempt to behave identically to threads relative
to the current version of L<threads> it supports (refer to $threads::VERSION),
even if the behavior is (or was) considered a bug.  At this time, this means
that shared variables will lose their pre-existing value at the time they are
shared and that splice will die if attempted on a shared scalar.

If you use forks for the first time as "use forks" and other loaded code uses
"use threads", then this threads behavior emulation does not apply. 

=head1 REQUIRED MODULES

 Acme::Damn (any)
 Attribute::Handlers (any)
 Devel::Symdump (any)
 File::Spec (any)
 if (any)
 IO::Socket (1.18)
 List::MoreUtils (0.15)
 Scalar::Util (1.11)
 Storable (any)
 Sys::SigAction (0.11)
 Test::More (any)
 Time::HiRes (any)

=head1 IMPLEMENTATION

This version is mostly written in Perl.  Inter-process communication
is done by using sockets, with the process that stores the shared variables
as the server and all the processes that function as threads, as clients.

=head2 why sockets?

The reason I chose sockets for inter-thread communication above using a shared
memory library, is that a blocking socket allows you to elegantly solve the
problem of a thread that is blocking for a certain event.  Any polling that
might occur, is not occurring at the Perl level, but at the level of the
socket, which should be much better and probably very optimized already.

=head1 EXTRA CLASS METHODS

Apart from the standard class methods, the following class methods are supplied
by the "forks" threads implementation.

=head2 isthread

 unless (fork) {
   threads->isthread; # this process is a detached thread now
   exit;              # can not return values, as thread is detached
 }

The C<isthread> class method attempt to make a connection with the shared
variables process.  If it succeeds, then the process will function as a
detached thread and will allow all the threads methods to operate.

This method is mainly intended to be used from within a child-init handler
in a pre-forking Apache server.  All the children that handle requests become
threads as far as Perl is concerned, allowing you to use shared variables
between all of the Apache processes.  See L<Apache::forks> for more information.

=head2 debug

 threads->debug( 1 );
 $debug = threads->debug;

The "debug" class method allows you to (re)set a flag which causes extensive
debugging output of the communication between threads to be output to STDERR.
The format is still subject to change and therefore still undocumented.

Debugging can B<only> be switched on by defining the environment variable
C<THREADS_DEBUG>.  If the environment variable does not exist when the forks.pm
module is compiled, then all debugging code will be optimised away to create
a better performance.  If the environment variable has a true value, then
debugging will also be enabled from the start.

=head1 EXTRA FEATURES

=head2 Native threads 'to-the-letter' emulation mode

By default, forks behaves slightly differently than native ithreads, regarding
shared variables.  Specifically, native threads does not support splice() on
shared arrays, nor does it retain any pre-existing values of arrays or hashes
when they are shared; however, forks supports all of these functions.  These are
behaviors are considered limitations/bugs in the current native ithread
implementation.

To allow for complete drop-in compatibility with scripts and modules written for
threads.pm, you may specify the environment variable C<THREADS_NATIVE_EMULATION>
to a true value before running your script.  This will instruct forks to behave
exactly as native ithreads would in the above noted situations.

This mode may also be enabled by default (without requiring this environment variable
if you do not have a threaded Perl and wish to install forks as a full drop-in
replacement.  See L</"Perl built without native ithreads"> for more information.

=head2 Deadlock detection

Forks also offers a full thread deadlock detection engine, to help discover
and optionally resolve locking issues in threaded applications.  See
L<forks::shared/"Deadlock detection and resolution"> for more information.

=head2 Perl debugger support

Forks supports basic compabitility with the Perl debugger.  By default, only the
main thread to the active terminal (TTY), allowing for debugging of scripts where
child threads are run as background tasks without any extra steps.

If you wish to debug code executed in child threads, you may need to perform a few
steps to prepare your environment for multi-threaded debugging.

The simplest option is run your script in xterm, as Perl will automatically create
additional xterm windows for each child thread that encounters a debugger breakpoint.

Otherwise, you will need to manually tell Perl how to map a control of thread to a
TTY.  Two undocumented features exist in the Perl debugger:

1. Define global variable C<$DB::fork_TTY> as the first stem in the subroutine for
a thread.  The value must be a valid TTY name, such as '/dev/pts/1' or '/dev/ttys001';
valid names may vary across platforms.  For example:

    threads->new(sub {
        $DB::fork_TTY = '/dev/tty003'; #tie thread to TTY 3
        ...
    });
    
Also, the TTY must be active and idle prior to the thread executing.  This normally
is accomplished by opening a new local or remote session to your machine, identifying
the TTY via `tty`, and then typing `sleep 10000000` to prevent user input from being
passed to the command line while you are debugging.

When the debugger halts at a breakpoint in your code in a child thread, all output and
user input will be managed via this TTY.

2. Define subroutine DB::get_fork_TTY()

This subroutine will execute once each child thread as soon as it has spawned.  Thus,
you can create a new TTY, or simply bind to an existng, active TTY.  In this subroutine,
you should define a unique, valid TTY name for the global variable C<$DB::fork_TTY>.

For example, to dynamically spawn a new xterm session and bind a new thread to it, you
could do the following:

sub DB::get_fork_TTY {
    open XT, q[3>&1 xterm -title 'Forked Perl debugger' -e sh -c 'tty1>&3;\ sleep 10000000' |];
    $DB::fork_TTY = <XT>;
    chomp $DB::fork_TTY;
}

For more information and tips, refer to this excellent Perl Monks thread:
L<<a href="http://www.perlmonks.org/?node_id=128283">Debugging Several Proccesses
at Same Time</a>>.

=head2 INET socket IP mask

For security, inter-thread communication INET sockets only will allow connections
from the default local machine IPv4 loopback address (e.g 127.0.0.1).  However,
this filter may be modified by defining the environment variable C<THREADS_IP_MASK>
with a standard perl regular expression (or with no value, which would disable the
filter).

=head2 UNIX socket support

For users who do not wish to (or can not) use TCP sockets, UNIX socket support
is available.  This can be B<only> switched on by defining the environment
variable C<THREADS_SOCKET_UNIX>.  If the environment variable has a true value, then
UNIX sockets will be used instead of the default TCP sockets.  Socket descriptors 
are currently written to /var/tmp and given a+rw access by default (for cleanest 
functional support on multi-user systems).

This feature is excellent for applications that require extra security, as it
does not expose forks.pm to any INET vunerabilities your system may be
subject to (i.e. systems not protected by a firewall).  It also may
provide an additional performance boost, as there is less system overhead
necessary to handle UNIX vs INET socket communication.

=head2 Co-existance with fork-aware modules and environments

For modules that actively monitor and clean up after defunct child processes
like L<POE>, forks has added support to switch the methodology used to maintain
thraad group state.  This feature is switched on by defining the environment
variable C<THREADS_DAEMON_MODEL>.  An example use might be:

    THREADS_DAEMON_MODEL=1 perl -Mforks -MPOE threadapplication

This function essentially reverses the parent-child relationship between the
main thread and the thread state process that forks.pm uses.  Extra care has
gone into retaining full system signal support and compatibility when using
this mode, so it should be quite stable.

=head1 NOTES

Some important items you should be aware of.

=head2 Signal behavior

Unlike ithreads, signals being sent are standard OS signals, so you should
program defensively if you plan to use inter-thread signals.

Also, be aware that certain signals may untrappable depending on the target
platform, such as SIGKILL and SIGSTOP.  Thus, it is recommended you only use
normal signals (such as TERM, INT, HUP, USR1, USR2) for inter-thread signal
handling.

=head2 exit() behavior

If you call exit() in a thread other than the main thread and exit behavior
is configured to cause entire application to exit (default behavior), be aware
that all other threads will be agressively terminated using SIGKILL.  This
will cause END blocks and global destruction to be ignored in those threads.

This behavior conforms to the expected behavior of native Perl threads. The
only subtle difference is that the main thread will be signaled using SIGABRT
to immediately exit.

If you call C<fork()> but do not call <threads->isthread()>, then the child
process will default to the pre-existing CORE::GLOBAL::exit() or CORE::exit()
behavior.  Note that such processes are exempt from application global
termination if exit() is called in a thread, so you must manually clean up
child processes created in this manner before exiting your threaded application.

=head2 END block behavior

In native ithreads, END blocks are only executed in the thread in which the
code was loaded/evaluated.  However, in forks, END blocks are processed in
all threads that are aware of such code segments (i.e. threads started after
modules with END blocks are loaded).  This may be considered a bug or a feature
depending on what your END blocks are doing, such as closing important external
resources for which each thread may have it's own handle.

In general, it is a good defensive programming practice to add the following to
your END blocks when you want to insure sure they only are evaluated in the thread
that they were created in:

    {
        my $tid = threads->tid if exists $INC{'threads.pm'};
        END {
            return if defined($tid) && $tid != threads->tid;
            # standard end block code goes here
        }
    }

This code is completely compatible with native ithreads.  Note that this
behavior may change in the future (at least with THREADS_NATIVE_EMULATION mode).

=head2 Modifying signals

Since the threads API provides a method to send signals between threads
(processes), untrapped normal and error signals are defined by forks with
a basic exit() shutdown function to provide safe termination.

Thus, if you (or any modules you use) modify signal handlers, it is important
that the signal handlers at least remain defined and are not undefined (for
whatever reason).  The system signal handler default, usually abnormal
process termination which skips END blocks, may cause undesired behavior if
a thread exits due to an unhandled signal.

In general, the following signals are considered "safe" to trap and use in
threads (depending on your system behavior when such signals are trapped):

    HUP INT PIPE TERM USR1 USR2 ABRT EMT QUIT TRAP

=head2 Modules that modify %SIG or use POSIX::sigaction()

To insure highest stability, forks ties some hooks into the global %SIG hash
to co-exist as peacefully as possible with user-defined signals.  This has a 
few subtle, but important implications:

    - As long as you modify signals using %SIG, you should never encounter any
    unexpected issues.

    - If you use POSIX::sigaction, it may subvert protections that forks has
    added to the signal handling system.  In normal circumstances, this will not
    create any run-time issues; however, if you also attempt to access shared
    variables in signal handlers or END blocks, you may encounter unexpected
    results.  Note: if you do use sigaction, please avoid overloading the ABRT
    signal in the main thread, as it is used for process group flow control.

=head2 Modules that modify $SIG{CHLD}

In order to be compatible with perl's core system() function on all platforms,
extra care has gone into implementing a smarter $SIG{CHLD} in forks.pm.  The
only functional effect is that you will never need to (or be able to) reap
threads (processes) if you define your own CHLD handler.

You may define the environment variable THREADS_SIGCHLD_IGNORE to to force 
forks to use 'IGNORE' on systems where a custom CHLD signal handler has been
automatically installed to support correct exit code of perl core system()
function.  Note that this should *not* be necessary unless you encounter specific
issues with the forks.pm CHLD signal handler.

=head2 $thr->wantarray() returns void after $thr->join or $thr->detach

Be aware that thread return context is purged and $thr->wantarray will return
void context after a thread is detached or joined.  This is done to minimize
memory in programs that spawn many (millions of) threads.  This differs from
default threads.pm behavior, but should be acceptable as the context no longer
serves a functional purpose after a join or detach.
Thus, if you still require thread context information after a join, be sure to
request and store the value of $thr->wantarray first.

=head2 $thr->get_stack_size() returns default after $thr->join or $thr->detach

Thread stack size information is purged and $thr->get_stack_size will return
the current threads default after a thread is detached or joined.  This is done
to minimize memory in programs that spawn many (millions of) threads.  This
differs from default threads.pm behavior, which retains per-thread stack size
information indefinitely.
Thus, if you require individual thread stack size information after a join or
detach, be sure to request and store the value of $thr->get_stack_size first.

=head2 Modules that modify CORE::GLOBAL::fork()

This modules goes to great lengths to insure that normal fork behavior is
seamlessly integrated into the threaded environment by overloading
CORE::GLOBAL::fork.  Thus, please refrain from overloading this function unless
absolutely necessary.  In such a case, forks.pm provides a set of four functions:

    _fork_pre
    _fork
    _fork_post_parent
    _fork_post_child

that represent all possible functional states before and after a fork occurs.
These states must be called to insure that fork() works for both threads and
normal fork calls.

Refer to forks.pm source code, *CORE::GLOBAL::fork = sub { ... } definition
as an example usage.  Please contact the author if you have any questions
regarding this.

=head1 CAVEATS

Some caveats that you need to be aware of.

=head2 Greater latency

Because of the use of sockets for inter-thread communication, there is an
inherent larger latency with the interaction between threads.  However, the
fact that TCP sockets are used, may open up the possibility to share threads
over more than one physical machine.

You may decrease some latency by using UNIX sockets (see L</"UNIX socket support">).

Also, you may wish to try L<forks::BerkeleyDB>, which has shown signifigant performance
gains and consistent throughoutput in applications requiring high-concurrency shared
variable access.

=head2 Module CLONE & CLONE_SKIP functions and threads

In rare cases, module CLONE functions may have issues when being auto-executed
by a new thread (forked process).  This only affects modules that use XS data
(objects or struts) created by to external C libraries.  If a module attempts
to CLONE non-fork safe XS data, at worst it may core dump only the newly
created thread (process).

If CLONE_SKIP function is defined in a package and it returns a true value, all
objects of this class type will be undefined in new threads.  This is generally the
same behavior as native threads with Perl 5.8.7 and later.  See <<a href="http://perldoc.perl.org/perlmod.html#Making-your-module-threadsafe-threadsafe-thread-safe-module%2c-threadsafe-module%2c-thread-safe-CLONE-CLONE_SKIP-thread-threads-ithread">perlmod</a>>
for more information.

However, two subtle behavior variances exist relative to native Perl threads:

    1. The actual undefining of variables occurs in the child thread.  This should
    be portable with all non-perl modules, as long as those module datastructures can be
    safely garbage collected in the child thread (note that DESTROY will not be called).
    
    2. Arrays and hashes will be emptied and unblessed, but value will not be converted
    to an undef scalar ref.  This differs from native threads, where all references
    become an undef scalar ref.  This should be generally harmless, as long as you are
    careful with variable state checks (e.g. check whether reference is still blessed,
    not whether the reftype has changed, to determine if it is still a valid object
    in a new thread).

Overall, if you treat potentially sensitive resources (such as L<DBI> driver instances) as 
non-thread-safe by default and close these resources prior to creating a new
thread, you should never encounter any portability issues.

=head2 Can't return unshared filehandles from threads

Currently, it is not possible to return a file handle from a thread to the
thread that is joining it.  Attempting to do so will throw a terminal error.
However, if you share the filehandle first with L<forks::shared>, you can safely
return the shared filehandle.

=head2 Signals and safe-signal enabled Perl

In order to use signals, you must be using perl 5.8 compiled with safe signal
support.  Otherwise, you'll get a terminal error like "Cannot signal threads
without safe signals" if you try to use signal functions.

=head2 Source filter

To get forks.pm working on Perl 5.6.x, it was necessary to use a source
filter to ensure a smooth upgrade path from using forks under Perl 5.6.x to
Perl 5.8.x and higher.  The source filter used is pretty simple and may
prove to be too simple.  Please report any problems that you may find when
running under 5.6.x.

=head1 TODO

See the TODO file in the distribution.

=head1 KNOWN PROBLEMS

These problems are known and will hopefully be fixed in the future:

=over 2

=item test-suite exits in a weird way

Although there are no errors in the test-suite, the test harness sometimes
thinks there is something wrong because of an unexpected exit() value.  This
is an issue with Test::More's END block, which wasn't designed to co-exist
with a threads environment and forked processes.  Hopefully, that module will
be patched in the future, but for now, the warnings are harmless and may be
safely ignored.

And of course, there might be other, undiscovered issues.  Patches are welcome!

=back

=head1 CREDITS

Refer to the C<CREDITS> file included in the distribution.

=head1 CURRENT AUTHOR AND MAINTAINER

Eric Rybski <rybskej@yahoo.com>.  Please send all module inquries to me.

=head1 ORIGINAL AUTHOR

Elizabeth Mattijsen, <liz@dijkmat.nl>.

=head1 COPYRIGHT

Copyright (c)
 2005-2010 Eric Rybski <rybskej@yahoo.com>,
 2002-2004 Elizabeth Mattijsen <liz@dijkmat.nl>.
All rights reserved.  This program is free software; you can redistribute it
and/or modify it under the same terms as Perl itself.

=head1 SEE ALSO

L<threads>, L<forks::BerkeleyDB>, L<Apache::forks>.

=cut