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 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903
|
/**********************************************************************
thread.c -
$Author$
Copyright (C) 2004-2007 Koichi Sasada
**********************************************************************/
/*
YARV Thread Design
model 1: Userlevel Thread
Same as traditional ruby thread.
model 2: Native Thread with Global VM lock
Using pthread (or Windows thread) and Ruby threads run concurrent.
model 3: Native Thread with fine grain lock
Using pthread and Ruby threads run concurrent or parallel.
model 4: M:N User:Native threads with Global VM lock
Combination of model 1 and 2
model 5: M:N User:Native thread with fine grain lock
Combination of model 1 and 3
------------------------------------------------------------------------
model 2:
A thread has mutex (GVL: Global VM Lock or Giant VM Lock) can run.
When thread scheduling, running thread release GVL. If running thread
try blocking operation, this thread must release GVL and another
thread can continue this flow. After blocking operation, thread
must check interrupt (RUBY_VM_CHECK_INTS).
Every VM can run parallel.
Ruby threads are scheduled by OS thread scheduler.
------------------------------------------------------------------------
model 3:
Every threads run concurrent or parallel and to access shared object
exclusive access control is needed. For example, to access String
object or Array object, fine grain lock must be locked every time.
*/
/*
* FD_SET, FD_CLR and FD_ISSET have a small sanity check when using glibc
* 2.15 or later and set _FORTIFY_SOURCE > 0.
* However, the implementation is wrong. Even though Linux's select(2)
* supports large fd size (>FD_SETSIZE), it wrongly assumes fd is always
* less than FD_SETSIZE (i.e. 1024). And then when enabling HAVE_RB_FD_INIT,
* it doesn't work correctly and makes program abort. Therefore we need to
* disable FORTIFY_SOURCE until glibc fixes it.
*/
#undef _FORTIFY_SOURCE
#undef __USE_FORTIFY_LEVEL
#define __USE_FORTIFY_LEVEL 0
/* for model 2 */
#include "ruby/internal/config.h"
#ifdef __linux__
// Normally, gcc(1) translates calls to alloca() with inlined code. This is not done when either the -ansi, -std=c89, -std=c99, or the -std=c11 option is given and the header <alloca.h> is not included.
# include <alloca.h>
#endif
#define TH_SCHED(th) (&(th)->ractor->threads.sched)
#include "eval_intern.h"
#include "hrtime.h"
#include "internal.h"
#include "internal/class.h"
#include "internal/cont.h"
#include "internal/error.h"
#include "internal/gc.h"
#include "internal/hash.h"
#include "internal/io.h"
#include "internal/object.h"
#include "internal/proc.h"
#include "ruby/fiber/scheduler.h"
#include "internal/signal.h"
#include "internal/thread.h"
#include "internal/time.h"
#include "internal/warnings.h"
#include "iseq.h"
#include "rjit.h"
#include "ruby/debug.h"
#include "ruby/io.h"
#include "ruby/thread.h"
#include "ruby/thread_native.h"
#include "timev.h"
#include "vm_core.h"
#include "ractor_core.h"
#include "vm_debug.h"
#include "vm_sync.h"
#if USE_RJIT && defined(HAVE_SYS_WAIT_H)
#include <sys/wait.h>
#endif
#ifndef USE_NATIVE_THREAD_PRIORITY
#define USE_NATIVE_THREAD_PRIORITY 0
#define RUBY_THREAD_PRIORITY_MAX 3
#define RUBY_THREAD_PRIORITY_MIN -3
#endif
static VALUE rb_cThreadShield;
static VALUE sym_immediate;
static VALUE sym_on_blocking;
static VALUE sym_never;
#define THREAD_LOCAL_STORAGE_INITIALISED FL_USER13
#define THREAD_LOCAL_STORAGE_INITIALISED_P(th) RB_FL_TEST_RAW((th), THREAD_LOCAL_STORAGE_INITIALISED)
static inline VALUE
rb_thread_local_storage(VALUE thread)
{
if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
rb_ivar_set(thread, idLocals, rb_hash_new());
RB_FL_SET_RAW(thread, THREAD_LOCAL_STORAGE_INITIALISED);
}
return rb_ivar_get(thread, idLocals);
}
enum SLEEP_FLAGS {
SLEEP_DEADLOCKABLE = 0x01,
SLEEP_SPURIOUS_CHECK = 0x02,
SLEEP_ALLOW_SPURIOUS = 0x04,
SLEEP_NO_CHECKINTS = 0x08,
};
static void sleep_forever(rb_thread_t *th, unsigned int fl);
static int sleep_hrtime(rb_thread_t *, rb_hrtime_t, unsigned int fl);
static void rb_thread_sleep_deadly_allow_spurious_wakeup(VALUE blocker, VALUE timeout, rb_hrtime_t end);
static int rb_threadptr_dead(rb_thread_t *th);
static void rb_check_deadlock(rb_ractor_t *r);
static int rb_threadptr_pending_interrupt_empty_p(const rb_thread_t *th);
static const char *thread_status_name(rb_thread_t *th, int detail);
static int hrtime_update_expire(rb_hrtime_t *, const rb_hrtime_t);
NORETURN(static void async_bug_fd(const char *mesg, int errno_arg, int fd));
MAYBE_UNUSED(static int consume_communication_pipe(int fd));
static volatile int system_working = 1;
static rb_internal_thread_specific_key_t specific_key_count;
struct waiting_fd {
struct ccan_list_node wfd_node; /* <=> vm.waiting_fds */
rb_thread_t *th;
int fd;
struct rb_io_close_wait_list *busy;
};
/********************************************************************************/
#define THREAD_SYSTEM_DEPENDENT_IMPLEMENTATION
struct rb_blocking_region_buffer {
enum rb_thread_status prev_status;
};
static int unblock_function_set(rb_thread_t *th, rb_unblock_function_t *func, void *arg, int fail_if_interrupted);
static void unblock_function_clear(rb_thread_t *th);
static inline int blocking_region_begin(rb_thread_t *th, struct rb_blocking_region_buffer *region,
rb_unblock_function_t *ubf, void *arg, int fail_if_interrupted);
static inline void blocking_region_end(rb_thread_t *th, struct rb_blocking_region_buffer *region);
#define THREAD_BLOCKING_BEGIN(th) do { \
struct rb_thread_sched * const sched = TH_SCHED(th); \
RB_VM_SAVE_MACHINE_CONTEXT(th); \
thread_sched_to_waiting((sched), (th));
#define THREAD_BLOCKING_END(th) \
thread_sched_to_running((sched), (th)); \
rb_ractor_thread_switch(th->ractor, th); \
} while(0)
#ifdef __GNUC__
#ifdef HAVE_BUILTIN___BUILTIN_CHOOSE_EXPR_CONSTANT_P
#define only_if_constant(expr, notconst) __builtin_choose_expr(__builtin_constant_p(expr), (expr), (notconst))
#else
#define only_if_constant(expr, notconst) (__builtin_constant_p(expr) ? (expr) : (notconst))
#endif
#else
#define only_if_constant(expr, notconst) notconst
#endif
#define BLOCKING_REGION(th, exec, ubf, ubfarg, fail_if_interrupted) do { \
struct rb_blocking_region_buffer __region; \
if (blocking_region_begin(th, &__region, (ubf), (ubfarg), fail_if_interrupted) || \
/* always return true unless fail_if_interrupted */ \
!only_if_constant(fail_if_interrupted, TRUE)) { \
/* Important that this is inlined into the macro, and not part of \
* blocking_region_begin - see bug #20493 */ \
RB_VM_SAVE_MACHINE_CONTEXT(th); \
thread_sched_to_waiting(TH_SCHED(th), th); \
exec; \
blocking_region_end(th, &__region); \
}; \
} while(0)
/*
* returns true if this thread was spuriously interrupted, false otherwise
* (e.g. hit by Thread#run or ran a Ruby-level Signal.trap handler)
*/
#define RUBY_VM_CHECK_INTS_BLOCKING(ec) vm_check_ints_blocking(ec)
static inline int
vm_check_ints_blocking(rb_execution_context_t *ec)
{
rb_thread_t *th = rb_ec_thread_ptr(ec);
if (LIKELY(rb_threadptr_pending_interrupt_empty_p(th))) {
if (LIKELY(!RUBY_VM_INTERRUPTED_ANY(ec))) return FALSE;
}
else {
th->pending_interrupt_queue_checked = 0;
RUBY_VM_SET_INTERRUPT(ec);
}
return rb_threadptr_execute_interrupts(th, 1);
}
int
rb_vm_check_ints_blocking(rb_execution_context_t *ec)
{
return vm_check_ints_blocking(ec);
}
/*
* poll() is supported by many OSes, but so far Linux is the only
* one we know of that supports using poll() in all places select()
* would work.
*/
#if defined(HAVE_POLL)
# if defined(__linux__)
# define USE_POLL
# endif
# if defined(__FreeBSD_version) && __FreeBSD_version >= 1100000
# define USE_POLL
/* FreeBSD does not set POLLOUT when POLLHUP happens */
# define POLLERR_SET (POLLHUP | POLLERR)
# endif
#endif
static void
timeout_prepare(rb_hrtime_t **to, rb_hrtime_t *rel, rb_hrtime_t *end,
const struct timeval *timeout)
{
if (timeout) {
*rel = rb_timeval2hrtime(timeout);
*end = rb_hrtime_add(rb_hrtime_now(), *rel);
*to = rel;
}
else {
*to = 0;
}
}
MAYBE_UNUSED(NOINLINE(static int thread_start_func_2(rb_thread_t *th, VALUE *stack_start)));
MAYBE_UNUSED(static bool th_has_dedicated_nt(const rb_thread_t *th));
MAYBE_UNUSED(static int waitfd_to_waiting_flag(int wfd_event));
#include THREAD_IMPL_SRC
/*
* TODO: somebody with win32 knowledge should be able to get rid of
* timer-thread by busy-waiting on signals. And it should be possible
* to make the GVL in thread_pthread.c be platform-independent.
*/
#ifndef BUSY_WAIT_SIGNALS
# define BUSY_WAIT_SIGNALS (0)
#endif
#ifndef USE_EVENTFD
# define USE_EVENTFD (0)
#endif
#include "thread_sync.c"
void
rb_nativethread_lock_initialize(rb_nativethread_lock_t *lock)
{
rb_native_mutex_initialize(lock);
}
void
rb_nativethread_lock_destroy(rb_nativethread_lock_t *lock)
{
rb_native_mutex_destroy(lock);
}
void
rb_nativethread_lock_lock(rb_nativethread_lock_t *lock)
{
rb_native_mutex_lock(lock);
}
void
rb_nativethread_lock_unlock(rb_nativethread_lock_t *lock)
{
rb_native_mutex_unlock(lock);
}
static int
unblock_function_set(rb_thread_t *th, rb_unblock_function_t *func, void *arg, int fail_if_interrupted)
{
do {
if (fail_if_interrupted) {
if (RUBY_VM_INTERRUPTED_ANY(th->ec)) {
return FALSE;
}
}
else {
RUBY_VM_CHECK_INTS(th->ec);
}
rb_native_mutex_lock(&th->interrupt_lock);
} while (!th->ec->raised_flag && RUBY_VM_INTERRUPTED_ANY(th->ec) &&
(rb_native_mutex_unlock(&th->interrupt_lock), TRUE));
VM_ASSERT(th->unblock.func == NULL);
th->unblock.func = func;
th->unblock.arg = arg;
rb_native_mutex_unlock(&th->interrupt_lock);
return TRUE;
}
static void
unblock_function_clear(rb_thread_t *th)
{
rb_native_mutex_lock(&th->interrupt_lock);
th->unblock.func = 0;
rb_native_mutex_unlock(&th->interrupt_lock);
}
static void
rb_threadptr_interrupt_common(rb_thread_t *th, int trap)
{
RUBY_DEBUG_LOG("th:%u trap:%d", rb_th_serial(th), trap);
rb_native_mutex_lock(&th->interrupt_lock);
{
if (trap) {
RUBY_VM_SET_TRAP_INTERRUPT(th->ec);
}
else {
RUBY_VM_SET_INTERRUPT(th->ec);
}
if (th->unblock.func != NULL) {
(th->unblock.func)(th->unblock.arg);
}
else {
/* none */
}
}
rb_native_mutex_unlock(&th->interrupt_lock);
}
void
rb_threadptr_interrupt(rb_thread_t *th)
{
RUBY_DEBUG_LOG("th:%u", rb_th_serial(th));
rb_threadptr_interrupt_common(th, 0);
}
static void
threadptr_trap_interrupt(rb_thread_t *th)
{
rb_threadptr_interrupt_common(th, 1);
}
static void
terminate_all(rb_ractor_t *r, const rb_thread_t *main_thread)
{
rb_thread_t *th = 0;
ccan_list_for_each(&r->threads.set, th, lt_node) {
if (th != main_thread) {
RUBY_DEBUG_LOG("terminate start th:%u status:%s", rb_th_serial(th), thread_status_name(th, TRUE));
rb_threadptr_pending_interrupt_enque(th, RUBY_FATAL_THREAD_TERMINATED);
rb_threadptr_interrupt(th);
RUBY_DEBUG_LOG("terminate done th:%u status:%s", rb_th_serial(th), thread_status_name(th, TRUE));
}
else {
RUBY_DEBUG_LOG("main thread th:%u", rb_th_serial(th));
}
}
}
static void
rb_threadptr_join_list_wakeup(rb_thread_t *thread)
{
while (thread->join_list) {
struct rb_waiting_list *join_list = thread->join_list;
// Consume the entry from the join list:
thread->join_list = join_list->next;
rb_thread_t *target_thread = join_list->thread;
if (target_thread->scheduler != Qnil && join_list->fiber) {
rb_fiber_scheduler_unblock(target_thread->scheduler, target_thread->self, rb_fiberptr_self(join_list->fiber));
}
else {
rb_threadptr_interrupt(target_thread);
switch (target_thread->status) {
case THREAD_STOPPED:
case THREAD_STOPPED_FOREVER:
target_thread->status = THREAD_RUNNABLE;
break;
default:
break;
}
}
}
}
void
rb_threadptr_unlock_all_locking_mutexes(rb_thread_t *th)
{
while (th->keeping_mutexes) {
rb_mutex_t *mutex = th->keeping_mutexes;
th->keeping_mutexes = mutex->next_mutex;
// rb_warn("mutex #<%p> was not unlocked by thread #<%p>", (void *)mutex, (void*)th);
const char *error_message = rb_mutex_unlock_th(mutex, th, mutex->fiber);
if (error_message) rb_bug("invalid keeping_mutexes: %s", error_message);
}
}
void
rb_thread_terminate_all(rb_thread_t *th)
{
rb_ractor_t *cr = th->ractor;
rb_execution_context_t * volatile ec = th->ec;
volatile int sleeping = 0;
if (cr->threads.main != th) {
rb_bug("rb_thread_terminate_all: called by child thread (%p, %p)",
(void *)cr->threads.main, (void *)th);
}
/* unlock all locking mutexes */
rb_threadptr_unlock_all_locking_mutexes(th);
EC_PUSH_TAG(ec);
if (EC_EXEC_TAG() == TAG_NONE) {
retry:
RUBY_DEBUG_LOG("th:%u", rb_th_serial(th));
terminate_all(cr, th);
while (rb_ractor_living_thread_num(cr) > 1) {
rb_hrtime_t rel = RB_HRTIME_PER_SEC;
/*q
* Thread exiting routine in thread_start_func_2 notify
* me when the last sub-thread exit.
*/
sleeping = 1;
native_sleep(th, &rel);
RUBY_VM_CHECK_INTS_BLOCKING(ec);
sleeping = 0;
}
}
else {
/*
* When caught an exception (e.g. Ctrl+C), let's broadcast
* kill request again to ensure killing all threads even
* if they are blocked on sleep, mutex, etc.
*/
if (sleeping) {
sleeping = 0;
goto retry;
}
}
EC_POP_TAG();
}
void rb_threadptr_root_fiber_terminate(rb_thread_t *th);
static void
thread_cleanup_func_before_exec(void *th_ptr)
{
rb_thread_t *th = th_ptr;
th->status = THREAD_KILLED;
// The thread stack doesn't exist in the forked process:
th->ec->machine.stack_start = th->ec->machine.stack_end = NULL;
rb_threadptr_root_fiber_terminate(th);
}
static void
thread_cleanup_func(void *th_ptr, int atfork)
{
rb_thread_t *th = th_ptr;
th->locking_mutex = Qfalse;
thread_cleanup_func_before_exec(th_ptr);
/*
* Unfortunately, we can't release native threading resource at fork
* because libc may have unstable locking state therefore touching
* a threading resource may cause a deadlock.
*/
if (atfork) {
th->nt = NULL;
return;
}
rb_native_mutex_destroy(&th->interrupt_lock);
}
static VALUE rb_threadptr_raise(rb_thread_t *, int, VALUE *);
static VALUE rb_thread_to_s(VALUE thread);
void
ruby_thread_init_stack(rb_thread_t *th)
{
native_thread_init_stack(th);
}
const VALUE *
rb_vm_proc_local_ep(VALUE proc)
{
const VALUE *ep = vm_proc_ep(proc);
if (ep) {
return rb_vm_ep_local_ep(ep);
}
else {
return NULL;
}
}
// for ractor, defined in vm.c
VALUE rb_vm_invoke_proc_with_self(rb_execution_context_t *ec, rb_proc_t *proc, VALUE self,
int argc, const VALUE *argv, int kw_splat, VALUE passed_block_handler);
static VALUE
thread_do_start_proc(rb_thread_t *th)
{
VALUE args = th->invoke_arg.proc.args;
const VALUE *args_ptr;
int args_len;
VALUE procval = th->invoke_arg.proc.proc;
rb_proc_t *proc;
GetProcPtr(procval, proc);
th->ec->errinfo = Qnil;
th->ec->root_lep = rb_vm_proc_local_ep(procval);
th->ec->root_svar = Qfalse;
vm_check_ints_blocking(th->ec);
if (th->invoke_type == thread_invoke_type_ractor_proc) {
VALUE self = rb_ractor_self(th->ractor);
VM_ASSERT(FIXNUM_P(args));
args_len = FIX2INT(args);
args_ptr = ALLOCA_N(VALUE, args_len);
rb_ractor_receive_parameters(th->ec, th->ractor, args_len, (VALUE *)args_ptr);
vm_check_ints_blocking(th->ec);
return rb_vm_invoke_proc_with_self(
th->ec, proc, self,
args_len, args_ptr,
th->invoke_arg.proc.kw_splat,
VM_BLOCK_HANDLER_NONE
);
}
else {
args_len = RARRAY_LENINT(args);
if (args_len < 8) {
/* free proc.args if the length is enough small */
args_ptr = ALLOCA_N(VALUE, args_len);
MEMCPY((VALUE *)args_ptr, RARRAY_CONST_PTR(args), VALUE, args_len);
th->invoke_arg.proc.args = Qnil;
}
else {
args_ptr = RARRAY_CONST_PTR(args);
}
vm_check_ints_blocking(th->ec);
return rb_vm_invoke_proc(
th->ec, proc,
args_len, args_ptr,
th->invoke_arg.proc.kw_splat,
VM_BLOCK_HANDLER_NONE
);
}
}
static VALUE
thread_do_start(rb_thread_t *th)
{
native_set_thread_name(th);
VALUE result = Qundef;
switch (th->invoke_type) {
case thread_invoke_type_proc:
result = thread_do_start_proc(th);
break;
case thread_invoke_type_ractor_proc:
result = thread_do_start_proc(th);
rb_ractor_atexit(th->ec, result);
break;
case thread_invoke_type_func:
result = (*th->invoke_arg.func.func)(th->invoke_arg.func.arg);
break;
case thread_invoke_type_none:
rb_bug("unreachable");
}
return result;
}
void rb_ec_clear_current_thread_trace_func(const rb_execution_context_t *ec);
static int
thread_start_func_2(rb_thread_t *th, VALUE *stack_start)
{
STACK_GROW_DIR_DETECTION;
RUBY_DEBUG_LOG("th:%u", rb_th_serial(th));
VM_ASSERT(th != th->vm->ractor.main_thread);
enum ruby_tag_type state;
VALUE errinfo = Qnil;
rb_thread_t *ractor_main_th = th->ractor->threads.main;
// setup ractor
if (rb_ractor_status_p(th->ractor, ractor_blocking)) {
RB_VM_LOCK();
{
rb_vm_ractor_blocking_cnt_dec(th->vm, th->ractor, __FILE__, __LINE__);
rb_ractor_t *r = th->ractor;
r->r_stdin = rb_io_prep_stdin();
r->r_stdout = rb_io_prep_stdout();
r->r_stderr = rb_io_prep_stderr();
}
RB_VM_UNLOCK();
}
// Ensure that we are not joinable.
VM_ASSERT(UNDEF_P(th->value));
int fiber_scheduler_closed = 0, event_thread_end_hooked = 0;
VALUE result = Qundef;
EC_PUSH_TAG(th->ec);
if ((state = EC_EXEC_TAG()) == TAG_NONE) {
EXEC_EVENT_HOOK(th->ec, RUBY_EVENT_THREAD_BEGIN, th->self, 0, 0, 0, Qundef);
SAVE_ROOT_JMPBUF(th, result = thread_do_start(th));
}
if (!fiber_scheduler_closed) {
fiber_scheduler_closed = 1;
rb_fiber_scheduler_set(Qnil);
}
if (!event_thread_end_hooked) {
event_thread_end_hooked = 1;
EXEC_EVENT_HOOK(th->ec, RUBY_EVENT_THREAD_END, th->self, 0, 0, 0, Qundef);
}
if (state == TAG_NONE) {
// This must be set AFTER doing all user-level code. At this point, the thread is effectively finished and calls to `Thread#join` will succeed.
th->value = result;
} else {
errinfo = th->ec->errinfo;
VALUE exc = rb_vm_make_jump_tag_but_local_jump(state, Qundef);
if (!NIL_P(exc)) errinfo = exc;
if (state == TAG_FATAL) {
if (th->invoke_type == thread_invoke_type_ractor_proc) {
rb_ractor_atexit(th->ec, Qnil);
}
/* fatal error within this thread, need to stop whole script */
}
else if (rb_obj_is_kind_of(errinfo, rb_eSystemExit)) {
/* exit on main_thread. */
}
else {
if (th->report_on_exception) {
VALUE mesg = rb_thread_to_s(th->self);
rb_str_cat_cstr(mesg, " terminated with exception (report_on_exception is true):\n");
rb_write_error_str(mesg);
rb_ec_error_print(th->ec, errinfo);
}
if (th->invoke_type == thread_invoke_type_ractor_proc) {
rb_ractor_atexit_exception(th->ec);
}
if (th->vm->thread_abort_on_exception ||
th->abort_on_exception || RTEST(ruby_debug)) {
/* exit on main_thread */
}
else {
errinfo = Qnil;
}
}
th->value = Qnil;
}
// The thread is effectively finished and can be joined.
VM_ASSERT(!UNDEF_P(th->value));
rb_threadptr_join_list_wakeup(th);
rb_threadptr_unlock_all_locking_mutexes(th);
if (th->invoke_type == thread_invoke_type_ractor_proc) {
rb_thread_terminate_all(th);
rb_ractor_teardown(th->ec);
}
th->status = THREAD_KILLED;
RUBY_DEBUG_LOG("killed th:%u", rb_th_serial(th));
if (th->vm->ractor.main_thread == th) {
ruby_stop(0);
}
if (RB_TYPE_P(errinfo, T_OBJECT)) {
/* treat with normal error object */
rb_threadptr_raise(ractor_main_th, 1, &errinfo);
}
EC_POP_TAG();
rb_ec_clear_current_thread_trace_func(th->ec);
/* locking_mutex must be Qfalse */
if (th->locking_mutex != Qfalse) {
rb_bug("thread_start_func_2: locking_mutex must not be set (%p:%"PRIxVALUE")",
(void *)th, th->locking_mutex);
}
if (ractor_main_th->status == THREAD_KILLED &&
th->ractor->threads.cnt <= 2 /* main thread and this thread */) {
/* I'm last thread. wake up main thread from rb_thread_terminate_all */
rb_threadptr_interrupt(ractor_main_th);
}
rb_check_deadlock(th->ractor);
rb_fiber_close(th->ec->fiber_ptr);
thread_cleanup_func(th, FALSE);
VM_ASSERT(th->ec->vm_stack == NULL);
if (th->invoke_type == thread_invoke_type_ractor_proc) {
// after rb_ractor_living_threads_remove()
// GC will happen anytime and this ractor can be collected (and destroy GVL).
// So gvl_release() should be before it.
thread_sched_to_dead(TH_SCHED(th), th);
rb_ractor_living_threads_remove(th->ractor, th);
}
else {
rb_ractor_living_threads_remove(th->ractor, th);
thread_sched_to_dead(TH_SCHED(th), th);
}
return 0;
}
struct thread_create_params {
enum thread_invoke_type type;
// for normal proc thread
VALUE args;
VALUE proc;
// for ractor
rb_ractor_t *g;
// for func
VALUE (*fn)(void *);
};
static void thread_specific_storage_alloc(rb_thread_t *th);
static VALUE
thread_create_core(VALUE thval, struct thread_create_params *params)
{
rb_execution_context_t *ec = GET_EC();
rb_thread_t *th = rb_thread_ptr(thval), *current_th = rb_ec_thread_ptr(ec);
int err;
thread_specific_storage_alloc(th);
if (OBJ_FROZEN(current_th->thgroup)) {
rb_raise(rb_eThreadError,
"can't start a new thread (frozen ThreadGroup)");
}
rb_fiber_inherit_storage(ec, th->ec->fiber_ptr);
switch (params->type) {
case thread_invoke_type_proc:
th->invoke_type = thread_invoke_type_proc;
th->invoke_arg.proc.args = params->args;
th->invoke_arg.proc.proc = params->proc;
th->invoke_arg.proc.kw_splat = rb_keyword_given_p();
break;
case thread_invoke_type_ractor_proc:
#if RACTOR_CHECK_MODE > 0
rb_ractor_setup_belonging_to(thval, rb_ractor_id(params->g));
#endif
th->invoke_type = thread_invoke_type_ractor_proc;
th->ractor = params->g;
th->ractor->threads.main = th;
th->invoke_arg.proc.proc = rb_proc_isolate_bang(params->proc);
th->invoke_arg.proc.args = INT2FIX(RARRAY_LENINT(params->args));
th->invoke_arg.proc.kw_splat = rb_keyword_given_p();
rb_ractor_send_parameters(ec, params->g, params->args);
break;
case thread_invoke_type_func:
th->invoke_type = thread_invoke_type_func;
th->invoke_arg.func.func = params->fn;
th->invoke_arg.func.arg = (void *)params->args;
break;
default:
rb_bug("unreachable");
}
th->priority = current_th->priority;
th->thgroup = current_th->thgroup;
th->pending_interrupt_queue = rb_ary_hidden_new(0);
th->pending_interrupt_queue_checked = 0;
th->pending_interrupt_mask_stack = rb_ary_dup(current_th->pending_interrupt_mask_stack);
RBASIC_CLEAR_CLASS(th->pending_interrupt_mask_stack);
rb_native_mutex_initialize(&th->interrupt_lock);
RUBY_DEBUG_LOG("r:%u th:%u", rb_ractor_id(th->ractor), rb_th_serial(th));
rb_ractor_living_threads_insert(th->ractor, th);
/* kick thread */
err = native_thread_create(th);
if (err) {
th->status = THREAD_KILLED;
rb_ractor_living_threads_remove(th->ractor, th);
rb_raise(rb_eThreadError, "can't create Thread: %s", strerror(err));
}
return thval;
}
#define threadptr_initialized(th) ((th)->invoke_type != thread_invoke_type_none)
/*
* call-seq:
* Thread.new { ... } -> thread
* Thread.new(*args, &proc) -> thread
* Thread.new(*args) { |args| ... } -> thread
*
* Creates a new thread executing the given block.
*
* Any +args+ given to ::new will be passed to the block:
*
* arr = []
* a, b, c = 1, 2, 3
* Thread.new(a,b,c) { |d,e,f| arr << d << e << f }.join
* arr #=> [1, 2, 3]
*
* A ThreadError exception is raised if ::new is called without a block.
*
* If you're going to subclass Thread, be sure to call super in your
* +initialize+ method, otherwise a ThreadError will be raised.
*/
static VALUE
thread_s_new(int argc, VALUE *argv, VALUE klass)
{
rb_thread_t *th;
VALUE thread = rb_thread_alloc(klass);
if (GET_RACTOR()->threads.main->status == THREAD_KILLED) {
rb_raise(rb_eThreadError, "can't alloc thread");
}
rb_obj_call_init_kw(thread, argc, argv, RB_PASS_CALLED_KEYWORDS);
th = rb_thread_ptr(thread);
if (!threadptr_initialized(th)) {
rb_raise(rb_eThreadError, "uninitialized thread - check `%"PRIsVALUE"#initialize'",
klass);
}
return thread;
}
/*
* call-seq:
* Thread.start([args]*) {|args| block } -> thread
* Thread.fork([args]*) {|args| block } -> thread
*
* Basically the same as ::new. However, if class Thread is subclassed, then
* calling +start+ in that subclass will not invoke the subclass's
* +initialize+ method.
*/
static VALUE
thread_start(VALUE klass, VALUE args)
{
struct thread_create_params params = {
.type = thread_invoke_type_proc,
.args = args,
.proc = rb_block_proc(),
};
return thread_create_core(rb_thread_alloc(klass), ¶ms);
}
static VALUE
threadptr_invoke_proc_location(rb_thread_t *th)
{
if (th->invoke_type == thread_invoke_type_proc) {
return rb_proc_location(th->invoke_arg.proc.proc);
}
else {
return Qnil;
}
}
/* :nodoc: */
static VALUE
thread_initialize(VALUE thread, VALUE args)
{
rb_thread_t *th = rb_thread_ptr(thread);
if (!rb_block_given_p()) {
rb_raise(rb_eThreadError, "must be called with a block");
}
else if (th->invoke_type != thread_invoke_type_none) {
VALUE loc = threadptr_invoke_proc_location(th);
if (!NIL_P(loc)) {
rb_raise(rb_eThreadError,
"already initialized thread - %"PRIsVALUE":%"PRIsVALUE,
RARRAY_AREF(loc, 0), RARRAY_AREF(loc, 1));
}
else {
rb_raise(rb_eThreadError, "already initialized thread");
}
}
else {
struct thread_create_params params = {
.type = thread_invoke_type_proc,
.args = args,
.proc = rb_block_proc(),
};
return thread_create_core(thread, ¶ms);
}
}
VALUE
rb_thread_create(VALUE (*fn)(void *), void *arg)
{
struct thread_create_params params = {
.type = thread_invoke_type_func,
.fn = fn,
.args = (VALUE)arg,
};
return thread_create_core(rb_thread_alloc(rb_cThread), ¶ms);
}
VALUE
rb_thread_create_ractor(rb_ractor_t *r, VALUE args, VALUE proc)
{
struct thread_create_params params = {
.type = thread_invoke_type_ractor_proc,
.g = r,
.args = args,
.proc = proc,
};
return thread_create_core(rb_thread_alloc(rb_cThread), ¶ms);
}
struct join_arg {
struct rb_waiting_list *waiter;
rb_thread_t *target;
VALUE timeout;
rb_hrtime_t *limit;
};
static VALUE
remove_from_join_list(VALUE arg)
{
struct join_arg *p = (struct join_arg *)arg;
rb_thread_t *target_thread = p->target;
if (target_thread->status != THREAD_KILLED) {
struct rb_waiting_list **join_list = &target_thread->join_list;
while (*join_list) {
if (*join_list == p->waiter) {
*join_list = (*join_list)->next;
break;
}
join_list = &(*join_list)->next;
}
}
return Qnil;
}
static int
thread_finished(rb_thread_t *th)
{
return th->status == THREAD_KILLED || !UNDEF_P(th->value);
}
static VALUE
thread_join_sleep(VALUE arg)
{
struct join_arg *p = (struct join_arg *)arg;
rb_thread_t *target_th = p->target, *th = p->waiter->thread;
rb_hrtime_t end = 0, *limit = p->limit;
if (limit) {
end = rb_hrtime_add(*limit, rb_hrtime_now());
}
while (!thread_finished(target_th)) {
VALUE scheduler = rb_fiber_scheduler_current();
if (scheduler != Qnil) {
rb_fiber_scheduler_block(scheduler, target_th->self, p->timeout);
// Check if the target thread is finished after blocking:
if (thread_finished(target_th)) break;
// Otherwise, a timeout occurred:
else return Qfalse;
}
else if (!limit) {
sleep_forever(th, SLEEP_DEADLOCKABLE | SLEEP_ALLOW_SPURIOUS | SLEEP_NO_CHECKINTS);
}
else {
if (hrtime_update_expire(limit, end)) {
RUBY_DEBUG_LOG("timeout target_th:%u", rb_th_serial(target_th));
return Qfalse;
}
th->status = THREAD_STOPPED;
native_sleep(th, limit);
}
RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
th->status = THREAD_RUNNABLE;
RUBY_DEBUG_LOG("interrupted target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
}
return Qtrue;
}
static VALUE
thread_join(rb_thread_t *target_th, VALUE timeout, rb_hrtime_t *limit)
{
rb_execution_context_t *ec = GET_EC();
rb_thread_t *th = ec->thread_ptr;
rb_fiber_t *fiber = ec->fiber_ptr;
if (th == target_th) {
rb_raise(rb_eThreadError, "Target thread must not be current thread");
}
if (th->ractor->threads.main == target_th) {
rb_raise(rb_eThreadError, "Target thread must not be main thread");
}
RUBY_DEBUG_LOG("target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
if (target_th->status != THREAD_KILLED) {
struct rb_waiting_list waiter;
waiter.next = target_th->join_list;
waiter.thread = th;
waiter.fiber = rb_fiberptr_blocking(fiber) ? NULL : fiber;
target_th->join_list = &waiter;
struct join_arg arg;
arg.waiter = &waiter;
arg.target = target_th;
arg.timeout = timeout;
arg.limit = limit;
if (!rb_ensure(thread_join_sleep, (VALUE)&arg, remove_from_join_list, (VALUE)&arg)) {
return Qnil;
}
}
RUBY_DEBUG_LOG("success target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
if (target_th->ec->errinfo != Qnil) {
VALUE err = target_th->ec->errinfo;
if (FIXNUM_P(err)) {
switch (err) {
case INT2FIX(TAG_FATAL):
RUBY_DEBUG_LOG("terminated target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
/* OK. killed. */
break;
default:
rb_bug("thread_join: Fixnum (%d) should not reach here.", FIX2INT(err));
}
}
else if (THROW_DATA_P(target_th->ec->errinfo)) {
rb_bug("thread_join: THROW_DATA should not reach here.");
}
else {
/* normal exception */
rb_exc_raise(err);
}
}
return target_th->self;
}
/*
* call-seq:
* thr.join -> thr
* thr.join(limit) -> thr
*
* The calling thread will suspend execution and run this +thr+.
*
* Does not return until +thr+ exits or until the given +limit+ seconds have
* passed.
*
* If the time limit expires, +nil+ will be returned, otherwise +thr+ is
* returned.
*
* Any threads not joined will be killed when the main program exits.
*
* If +thr+ had previously raised an exception and the ::abort_on_exception or
* $DEBUG flags are not set, (so the exception has not yet been processed), it
* will be processed at this time.
*
* a = Thread.new { print "a"; sleep(10); print "b"; print "c" }
* x = Thread.new { print "x"; Thread.pass; print "y"; print "z" }
* x.join # Let thread x finish, thread a will be killed on exit.
* #=> "axyz"
*
* The following example illustrates the +limit+ parameter.
*
* y = Thread.new { 4.times { sleep 0.1; puts 'tick... ' }}
* puts "Waiting" until y.join(0.15)
*
* This will produce:
*
* tick...
* Waiting
* tick...
* Waiting
* tick...
* tick...
*/
static VALUE
thread_join_m(int argc, VALUE *argv, VALUE self)
{
VALUE timeout = Qnil;
rb_hrtime_t rel = 0, *limit = 0;
if (rb_check_arity(argc, 0, 1)) {
timeout = argv[0];
}
// Convert the timeout eagerly, so it's always converted and deterministic
/*
* This supports INFINITY and negative values, so we can't use
* rb_time_interval right now...
*/
if (NIL_P(timeout)) {
/* unlimited */
}
else if (FIXNUM_P(timeout)) {
rel = rb_sec2hrtime(NUM2TIMET(timeout));
limit = &rel;
}
else {
limit = double2hrtime(&rel, rb_num2dbl(timeout));
}
return thread_join(rb_thread_ptr(self), timeout, limit);
}
/*
* call-seq:
* thr.value -> obj
*
* Waits for +thr+ to complete, using #join, and returns its value or raises
* the exception which terminated the thread.
*
* a = Thread.new { 2 + 2 }
* a.value #=> 4
*
* b = Thread.new { raise 'something went wrong' }
* b.value #=> RuntimeError: something went wrong
*/
static VALUE
thread_value(VALUE self)
{
rb_thread_t *th = rb_thread_ptr(self);
thread_join(th, Qnil, 0);
if (UNDEF_P(th->value)) {
// If the thread is dead because we forked th->value is still Qundef.
return Qnil;
}
return th->value;
}
/*
* Thread Scheduling
*/
static void
getclockofday(struct timespec *ts)
{
#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
return;
#endif
rb_timespec_now(ts);
}
/*
* Don't inline this, since library call is already time consuming
* and we don't want "struct timespec" on stack too long for GC
*/
NOINLINE(rb_hrtime_t rb_hrtime_now(void));
rb_hrtime_t
rb_hrtime_now(void)
{
struct timespec ts;
getclockofday(&ts);
return rb_timespec2hrtime(&ts);
}
/*
* at least gcc 7.2 and 7.3 complains about "rb_hrtime_t end"
* being uninitialized, maybe other versions, too.
*/
COMPILER_WARNING_PUSH
#if defined(__GNUC__) && __GNUC__ == 7 && __GNUC_MINOR__ <= 3
COMPILER_WARNING_IGNORED(-Wmaybe-uninitialized)
#endif
#ifndef PRIu64
#define PRIu64 PRI_64_PREFIX "u"
#endif
/*
* @end is the absolute time when @ts is set to expire
* Returns true if @end has past
* Updates @ts and returns false otherwise
*/
static int
hrtime_update_expire(rb_hrtime_t *timeout, const rb_hrtime_t end)
{
rb_hrtime_t now = rb_hrtime_now();
if (now > end) return 1;
RUBY_DEBUG_LOG("%"PRIu64" > %"PRIu64"", (uint64_t)end, (uint64_t)now);
*timeout = end - now;
return 0;
}
COMPILER_WARNING_POP
static int
sleep_hrtime(rb_thread_t *th, rb_hrtime_t rel, unsigned int fl)
{
enum rb_thread_status prev_status = th->status;
int woke;
rb_hrtime_t end = rb_hrtime_add(rb_hrtime_now(), rel);
th->status = THREAD_STOPPED;
RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
while (th->status == THREAD_STOPPED) {
native_sleep(th, &rel);
woke = vm_check_ints_blocking(th->ec);
if (woke && !(fl & SLEEP_SPURIOUS_CHECK))
break;
if (hrtime_update_expire(&rel, end))
break;
woke = 1;
}
th->status = prev_status;
return woke;
}
static int
sleep_hrtime_until(rb_thread_t *th, rb_hrtime_t end, unsigned int fl)
{
enum rb_thread_status prev_status = th->status;
int woke;
rb_hrtime_t rel = rb_hrtime_sub(end, rb_hrtime_now());
th->status = THREAD_STOPPED;
RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
while (th->status == THREAD_STOPPED) {
native_sleep(th, &rel);
woke = vm_check_ints_blocking(th->ec);
if (woke && !(fl & SLEEP_SPURIOUS_CHECK))
break;
if (hrtime_update_expire(&rel, end))
break;
woke = 1;
}
th->status = prev_status;
return woke;
}
static void
sleep_forever(rb_thread_t *th, unsigned int fl)
{
enum rb_thread_status prev_status = th->status;
enum rb_thread_status status;
int woke;
status = fl & SLEEP_DEADLOCKABLE ? THREAD_STOPPED_FOREVER : THREAD_STOPPED;
th->status = status;
if (!(fl & SLEEP_NO_CHECKINTS)) RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
while (th->status == status) {
if (fl & SLEEP_DEADLOCKABLE) {
rb_ractor_sleeper_threads_inc(th->ractor);
rb_check_deadlock(th->ractor);
}
{
native_sleep(th, 0);
}
if (fl & SLEEP_DEADLOCKABLE) {
rb_ractor_sleeper_threads_dec(th->ractor);
}
if (fl & SLEEP_ALLOW_SPURIOUS) {
break;
}
woke = vm_check_ints_blocking(th->ec);
if (woke && !(fl & SLEEP_SPURIOUS_CHECK)) {
break;
}
}
th->status = prev_status;
}
void
rb_thread_sleep_forever(void)
{
RUBY_DEBUG_LOG("forever");
sleep_forever(GET_THREAD(), SLEEP_SPURIOUS_CHECK);
}
void
rb_thread_sleep_deadly(void)
{
RUBY_DEBUG_LOG("deadly");
sleep_forever(GET_THREAD(), SLEEP_DEADLOCKABLE|SLEEP_SPURIOUS_CHECK);
}
static void
rb_thread_sleep_deadly_allow_spurious_wakeup(VALUE blocker, VALUE timeout, rb_hrtime_t end)
{
VALUE scheduler = rb_fiber_scheduler_current();
if (scheduler != Qnil) {
rb_fiber_scheduler_block(scheduler, blocker, timeout);
}
else {
RUBY_DEBUG_LOG("...");
if (end) {
sleep_hrtime_until(GET_THREAD(), end, SLEEP_SPURIOUS_CHECK);
}
else {
sleep_forever(GET_THREAD(), SLEEP_DEADLOCKABLE);
}
}
}
void
rb_thread_wait_for(struct timeval time)
{
rb_thread_t *th = GET_THREAD();
sleep_hrtime(th, rb_timeval2hrtime(&time), SLEEP_SPURIOUS_CHECK);
}
/*
* CAUTION: This function causes thread switching.
* rb_thread_check_ints() check ruby's interrupts.
* some interrupt needs thread switching/invoke handlers,
* and so on.
*/
void
rb_thread_check_ints(void)
{
RUBY_VM_CHECK_INTS_BLOCKING(GET_EC());
}
/*
* Hidden API for tcl/tk wrapper.
* There is no guarantee to perpetuate it.
*/
int
rb_thread_check_trap_pending(void)
{
return rb_signal_buff_size() != 0;
}
/* This function can be called in blocking region. */
int
rb_thread_interrupted(VALUE thval)
{
return (int)RUBY_VM_INTERRUPTED(rb_thread_ptr(thval)->ec);
}
void
rb_thread_sleep(int sec)
{
rb_thread_wait_for(rb_time_timeval(INT2FIX(sec)));
}
static void
rb_thread_schedule_limits(uint32_t limits_us)
{
if (!rb_thread_alone()) {
rb_thread_t *th = GET_THREAD();
RUBY_DEBUG_LOG("us:%u", (unsigned int)limits_us);
if (th->running_time_us >= limits_us) {
RUBY_DEBUG_LOG("switch %s", "start");
RB_VM_SAVE_MACHINE_CONTEXT(th);
thread_sched_yield(TH_SCHED(th), th);
rb_ractor_thread_switch(th->ractor, th);
RUBY_DEBUG_LOG("switch %s", "done");
}
}
}
void
rb_thread_schedule(void)
{
rb_thread_schedule_limits(0);
RUBY_VM_CHECK_INTS(GET_EC());
}
/* blocking region */
static inline int
blocking_region_begin(rb_thread_t *th, struct rb_blocking_region_buffer *region,
rb_unblock_function_t *ubf, void *arg, int fail_if_interrupted)
{
#ifdef RUBY_VM_CRITICAL_SECTION
VM_ASSERT(ruby_assert_critical_section_entered == 0);
#endif
VM_ASSERT(th == GET_THREAD());
region->prev_status = th->status;
if (unblock_function_set(th, ubf, arg, fail_if_interrupted)) {
th->blocking_region_buffer = region;
th->status = THREAD_STOPPED;
rb_ractor_blocking_threads_inc(th->ractor, __FILE__, __LINE__);
RUBY_DEBUG_LOG("thread_id:%p", (void *)th->nt->thread_id);
return TRUE;
}
else {
return FALSE;
}
}
static inline void
blocking_region_end(rb_thread_t *th, struct rb_blocking_region_buffer *region)
{
/* entry to ubf_list still permitted at this point, make it impossible: */
unblock_function_clear(th);
/* entry to ubf_list impossible at this point, so unregister is safe: */
unregister_ubf_list(th);
thread_sched_to_running(TH_SCHED(th), th);
rb_ractor_thread_switch(th->ractor, th);
th->blocking_region_buffer = 0;
rb_ractor_blocking_threads_dec(th->ractor, __FILE__, __LINE__);
if (th->status == THREAD_STOPPED) {
th->status = region->prev_status;
}
RUBY_DEBUG_LOG("end");
#ifndef _WIN32
// GET_THREAD() clears WSAGetLastError()
VM_ASSERT(th == GET_THREAD());
#endif
}
void *
rb_nogvl(void *(*func)(void *), void *data1,
rb_unblock_function_t *ubf, void *data2,
int flags)
{
void *val = 0;
rb_execution_context_t *ec = GET_EC();
rb_thread_t *th = rb_ec_thread_ptr(ec);
rb_vm_t *vm = rb_ec_vm_ptr(ec);
bool is_main_thread = vm->ractor.main_thread == th;
int saved_errno = 0;
VALUE ubf_th = Qfalse;
if ((ubf == RUBY_UBF_IO) || (ubf == RUBY_UBF_PROCESS)) {
ubf = ubf_select;
data2 = th;
}
else if (ubf && rb_ractor_living_thread_num(th->ractor) == 1 && is_main_thread) {
if (flags & RB_NOGVL_UBF_ASYNC_SAFE) {
vm->ubf_async_safe = 1;
}
}
BLOCKING_REGION(th, {
val = func(data1);
saved_errno = rb_errno();
}, ubf, data2, flags & RB_NOGVL_INTR_FAIL);
if (is_main_thread) vm->ubf_async_safe = 0;
if ((flags & RB_NOGVL_INTR_FAIL) == 0) {
RUBY_VM_CHECK_INTS_BLOCKING(ec);
}
if (ubf_th != Qfalse) {
thread_value(rb_thread_kill(ubf_th));
}
rb_errno_set(saved_errno);
return val;
}
/*
* rb_thread_call_without_gvl - permit concurrent/parallel execution.
* rb_thread_call_without_gvl2 - permit concurrent/parallel execution
* without interrupt process.
*
* rb_thread_call_without_gvl() does:
* (1) Check interrupts.
* (2) release GVL.
* Other Ruby threads may run in parallel.
* (3) call func with data1
* (4) acquire GVL.
* Other Ruby threads can not run in parallel any more.
* (5) Check interrupts.
*
* rb_thread_call_without_gvl2() does:
* (1) Check interrupt and return if interrupted.
* (2) release GVL.
* (3) call func with data1 and a pointer to the flags.
* (4) acquire GVL.
*
* If another thread interrupts this thread (Thread#kill, signal delivery,
* VM-shutdown request, and so on), `ubf()' is called (`ubf()' means
* "un-blocking function"). `ubf()' should interrupt `func()' execution by
* toggling a cancellation flag, canceling the invocation of a call inside
* `func()' or similar. Note that `ubf()' may not be called with the GVL.
*
* There are built-in ubfs and you can specify these ubfs:
*
* * RUBY_UBF_IO: ubf for IO operation
* * RUBY_UBF_PROCESS: ubf for process operation
*
* However, we can not guarantee our built-in ubfs interrupt your `func()'
* correctly. Be careful to use rb_thread_call_without_gvl(). If you don't
* provide proper ubf(), your program will not stop for Control+C or other
* shutdown events.
*
* "Check interrupts" on above list means checking asynchronous
* interrupt events (such as Thread#kill, signal delivery, VM-shutdown
* request, and so on) and calling corresponding procedures
* (such as `trap' for signals, raise an exception for Thread#raise).
* If `func()' finished and received interrupts, you may skip interrupt
* checking. For example, assume the following func() it reads data from file.
*
* read_func(...) {
* // (a) before read
* read(buffer); // (b) reading
* // (c) after read
* }
*
* If an interrupt occurs at (a) or (b), then `ubf()' cancels this
* `read_func()' and interrupts are checked. However, if an interrupt occurs
* at (c), after *read* operation is completed, checking interrupts is harmful
* because it causes irrevocable side-effect, the read data will vanish. To
* avoid such problem, the `read_func()' should be used with
* `rb_thread_call_without_gvl2()'.
*
* If `rb_thread_call_without_gvl2()' detects interrupt, it returns
* immediately. This function does not show when the execution was interrupted.
* For example, there are 4 possible timing (a), (b), (c) and before calling
* read_func(). You need to record progress of a read_func() and check
* the progress after `rb_thread_call_without_gvl2()'. You may need to call
* `rb_thread_check_ints()' correctly or your program can not process proper
* process such as `trap' and so on.
*
* NOTE: You can not execute most of Ruby C API and touch Ruby
* objects in `func()' and `ubf()', including raising an
* exception, because current thread doesn't acquire GVL
* (it causes synchronization problems). If you need to
* call ruby functions either use rb_thread_call_with_gvl()
* or read source code of C APIs and confirm safety by
* yourself.
*
* NOTE: In short, this API is difficult to use safely. I recommend you
* use other ways if you have. We lack experiences to use this API.
* Please report your problem related on it.
*
* NOTE: Releasing GVL and re-acquiring GVL may be expensive operations
* for a short running `func()'. Be sure to benchmark and use this
* mechanism when `func()' consumes enough time.
*
* Safe C API:
* * rb_thread_interrupted() - check interrupt flag
* * ruby_xmalloc(), ruby_xrealloc(), ruby_xfree() -
* they will work without GVL, and may acquire GVL when GC is needed.
*/
void *
rb_thread_call_without_gvl2(void *(*func)(void *), void *data1,
rb_unblock_function_t *ubf, void *data2)
{
return rb_nogvl(func, data1, ubf, data2, RB_NOGVL_INTR_FAIL);
}
void *
rb_thread_call_without_gvl(void *(*func)(void *data), void *data1,
rb_unblock_function_t *ubf, void *data2)
{
return rb_nogvl(func, data1, ubf, data2, 0);
}
static int
waitfd_to_waiting_flag(int wfd_event)
{
return wfd_event << 1;
}
static void
thread_io_setup_wfd(rb_thread_t *th, int fd, struct waiting_fd *wfd)
{
wfd->fd = fd;
wfd->th = th;
wfd->busy = NULL;
RB_VM_LOCK_ENTER();
{
ccan_list_add(&th->vm->waiting_fds, &wfd->wfd_node);
}
RB_VM_LOCK_LEAVE();
}
static void
thread_io_wake_pending_closer(struct waiting_fd *wfd)
{
bool has_waiter = wfd->busy && RB_TEST(wfd->busy->wakeup_mutex);
if (has_waiter) {
rb_mutex_lock(wfd->busy->wakeup_mutex);
}
/* Needs to be protected with RB_VM_LOCK because we don't know if
wfd is on the global list of pending FD ops or if it's on a
struct rb_io_close_wait_list close-waiter. */
RB_VM_LOCK_ENTER();
ccan_list_del(&wfd->wfd_node);
RB_VM_LOCK_LEAVE();
if (has_waiter) {
rb_thread_t *th = rb_thread_ptr(wfd->busy->closing_thread);
if (th->scheduler != Qnil) {
rb_fiber_scheduler_unblock(th->scheduler, wfd->busy->closing_thread, wfd->busy->closing_fiber);
} else {
rb_thread_wakeup(wfd->busy->closing_thread);
}
rb_mutex_unlock(wfd->busy->wakeup_mutex);
}
}
static int
thread_io_wait_events(rb_thread_t *th, rb_execution_context_t *ec, int fd, int events, struct timeval *timeout, struct waiting_fd *wfd)
{
#if defined(USE_MN_THREADS) && USE_MN_THREADS
if (!th_has_dedicated_nt(th) &&
(events || timeout) &&
th->blocking // no fiber scheduler
) {
int r;
rb_hrtime_t rel, *prel;
if (timeout) {
rel = rb_timeval2hrtime(timeout);
prel = &rel;
}
else {
prel = NULL;
}
VM_ASSERT(prel || (events & (RB_WAITFD_IN | RB_WAITFD_OUT)));
thread_io_setup_wfd(th, fd, wfd);
{
// wait readable/writable
r = thread_sched_wait_events(TH_SCHED(th), th, fd, waitfd_to_waiting_flag(events), prel);
}
thread_io_wake_pending_closer(wfd);
RUBY_VM_CHECK_INTS_BLOCKING(ec);
return r;
}
#endif // defined(USE_MN_THREADS) && USE_MN_THREADS
return 0;
}
VALUE
rb_thread_io_blocking_call(rb_blocking_function_t *func, void *data1, int fd, int events)
{
rb_execution_context_t * volatile ec = GET_EC();
rb_thread_t *th = rb_ec_thread_ptr(ec);
RUBY_DEBUG_LOG("th:%u fd:%d ev:%d", rb_th_serial(th), fd, events);
struct waiting_fd waiting_fd;
thread_io_wait_events(th, ec, fd, events, NULL, &waiting_fd);
volatile VALUE val = Qundef; /* shouldn't be used */
volatile int saved_errno = 0;
enum ruby_tag_type state;
// `errno` is only valid when there is an actual error - but we can't
// extract that from the return value of `func` alone, so we clear any
// prior `errno` value here so that we can later check if it was set by
// `func` or not (as opposed to some previously set value).
errno = 0;
thread_io_setup_wfd(th, fd, &waiting_fd);
EC_PUSH_TAG(ec);
if ((state = EC_EXEC_TAG()) == TAG_NONE) {
BLOCKING_REGION(waiting_fd.th, {
val = func(data1);
saved_errno = errno;
}, ubf_select, waiting_fd.th, FALSE);
}
EC_POP_TAG();
/*
* must be deleted before jump
* this will delete either from waiting_fds or on-stack struct rb_io_close_wait_list
*/
thread_io_wake_pending_closer(&waiting_fd);
if (state) {
EC_JUMP_TAG(ec, state);
}
/* TODO: check func() */
RUBY_VM_CHECK_INTS_BLOCKING(ec);
// If the error was a timeout, we raise a specific exception for that:
if (saved_errno == ETIMEDOUT) {
rb_raise(rb_eIOTimeoutError, "Blocking operation timed out!");
}
errno = saved_errno;
return val;
}
VALUE
rb_thread_io_blocking_region(rb_blocking_function_t *func, void *data1, int fd)
{
return rb_thread_io_blocking_call(func, data1, fd, 0);
}
/*
* rb_thread_call_with_gvl - re-enter the Ruby world after GVL release.
*
* After releasing GVL using
* rb_thread_call_without_gvl() you can not access Ruby values or invoke
* methods. If you need to access Ruby you must use this function
* rb_thread_call_with_gvl().
*
* This function rb_thread_call_with_gvl() does:
* (1) acquire GVL.
* (2) call passed function `func'.
* (3) release GVL.
* (4) return a value which is returned at (2).
*
* NOTE: You should not return Ruby object at (2) because such Object
* will not be marked.
*
* NOTE: If an exception is raised in `func', this function DOES NOT
* protect (catch) the exception. If you have any resources
* which should free before throwing exception, you need use
* rb_protect() in `func' and return a value which represents
* exception was raised.
*
* NOTE: This function should not be called by a thread which was not
* created as Ruby thread (created by Thread.new or so). In other
* words, this function *DOES NOT* associate or convert a NON-Ruby
* thread to a Ruby thread.
*/
void *
rb_thread_call_with_gvl(void *(*func)(void *), void *data1)
{
rb_thread_t *th = ruby_thread_from_native();
struct rb_blocking_region_buffer *brb;
struct rb_unblock_callback prev_unblock;
void *r;
if (th == 0) {
/* Error has occurred, but we can't use rb_bug()
* because this thread is not Ruby's thread.
* What should we do?
*/
bp();
fprintf(stderr, "[BUG] rb_thread_call_with_gvl() is called by non-ruby thread\n");
exit(EXIT_FAILURE);
}
brb = (struct rb_blocking_region_buffer *)th->blocking_region_buffer;
prev_unblock = th->unblock;
if (brb == 0) {
rb_bug("rb_thread_call_with_gvl: called by a thread which has GVL.");
}
blocking_region_end(th, brb);
/* enter to Ruby world: You can access Ruby values, methods and so on. */
r = (*func)(data1);
/* leave from Ruby world: You can not access Ruby values, etc. */
int released = blocking_region_begin(th, brb, prev_unblock.func, prev_unblock.arg, FALSE);
RUBY_ASSERT_ALWAYS(released);
RB_VM_SAVE_MACHINE_CONTEXT(th);
thread_sched_to_waiting(TH_SCHED(th), th);
return r;
}
/*
* ruby_thread_has_gvl_p - check if current native thread has GVL.
*
***
*** This API is EXPERIMENTAL!
*** We do not guarantee that this API remains in ruby 1.9.2 or later.
***
*/
int
ruby_thread_has_gvl_p(void)
{
rb_thread_t *th = ruby_thread_from_native();
if (th && th->blocking_region_buffer == 0) {
return 1;
}
else {
return 0;
}
}
/*
* call-seq:
* Thread.pass -> nil
*
* Give the thread scheduler a hint to pass execution to another thread.
* A running thread may or may not switch, it depends on OS and processor.
*/
static VALUE
thread_s_pass(VALUE klass)
{
rb_thread_schedule();
return Qnil;
}
/*****************************************************/
/*
* rb_threadptr_pending_interrupt_* - manage asynchronous error queue
*
* Async events such as an exception thrown by Thread#raise,
* Thread#kill and thread termination (after main thread termination)
* will be queued to th->pending_interrupt_queue.
* - clear: clear the queue.
* - enque: enqueue err object into queue.
* - deque: dequeue err object from queue.
* - active_p: return 1 if the queue should be checked.
*
* All rb_threadptr_pending_interrupt_* functions are called by
* a GVL acquired thread, of course.
* Note that all "rb_" prefix APIs need GVL to call.
*/
void
rb_threadptr_pending_interrupt_clear(rb_thread_t *th)
{
rb_ary_clear(th->pending_interrupt_queue);
}
void
rb_threadptr_pending_interrupt_enque(rb_thread_t *th, VALUE v)
{
rb_ary_push(th->pending_interrupt_queue, v);
th->pending_interrupt_queue_checked = 0;
}
static void
threadptr_check_pending_interrupt_queue(rb_thread_t *th)
{
if (!th->pending_interrupt_queue) {
rb_raise(rb_eThreadError, "uninitialized thread");
}
}
enum handle_interrupt_timing {
INTERRUPT_NONE,
INTERRUPT_IMMEDIATE,
INTERRUPT_ON_BLOCKING,
INTERRUPT_NEVER
};
static enum handle_interrupt_timing
rb_threadptr_pending_interrupt_from_symbol(rb_thread_t *th, VALUE sym)
{
if (sym == sym_immediate) {
return INTERRUPT_IMMEDIATE;
}
else if (sym == sym_on_blocking) {
return INTERRUPT_ON_BLOCKING;
}
else if (sym == sym_never) {
return INTERRUPT_NEVER;
}
else {
rb_raise(rb_eThreadError, "unknown mask signature");
}
}
static enum handle_interrupt_timing
rb_threadptr_pending_interrupt_check_mask(rb_thread_t *th, VALUE err)
{
VALUE mask;
long mask_stack_len = RARRAY_LEN(th->pending_interrupt_mask_stack);
const VALUE *mask_stack = RARRAY_CONST_PTR(th->pending_interrupt_mask_stack);
VALUE mod;
long i;
for (i=0; i<mask_stack_len; i++) {
mask = mask_stack[mask_stack_len-(i+1)];
if (SYMBOL_P(mask)) {
/* do not match RUBY_FATAL_THREAD_KILLED etc */
if (err != rb_cInteger) {
return rb_threadptr_pending_interrupt_from_symbol(th, mask);
}
else {
continue;
}
}
for (mod = err; mod; mod = RCLASS_SUPER(mod)) {
VALUE klass = mod;
VALUE sym;
if (BUILTIN_TYPE(mod) == T_ICLASS) {
klass = RBASIC(mod)->klass;
}
else if (mod != RCLASS_ORIGIN(mod)) {
continue;
}
if ((sym = rb_hash_aref(mask, klass)) != Qnil) {
return rb_threadptr_pending_interrupt_from_symbol(th, sym);
}
}
/* try to next mask */
}
return INTERRUPT_NONE;
}
static int
rb_threadptr_pending_interrupt_empty_p(const rb_thread_t *th)
{
return RARRAY_LEN(th->pending_interrupt_queue) == 0;
}
static int
rb_threadptr_pending_interrupt_include_p(rb_thread_t *th, VALUE err)
{
int i;
for (i=0; i<RARRAY_LEN(th->pending_interrupt_queue); i++) {
VALUE e = RARRAY_AREF(th->pending_interrupt_queue, i);
if (rb_obj_is_kind_of(e, err)) {
return TRUE;
}
}
return FALSE;
}
static VALUE
rb_threadptr_pending_interrupt_deque(rb_thread_t *th, enum handle_interrupt_timing timing)
{
#if 1 /* 1 to enable Thread#handle_interrupt, 0 to ignore it */
int i;
for (i=0; i<RARRAY_LEN(th->pending_interrupt_queue); i++) {
VALUE err = RARRAY_AREF(th->pending_interrupt_queue, i);
enum handle_interrupt_timing mask_timing = rb_threadptr_pending_interrupt_check_mask(th, CLASS_OF(err));
switch (mask_timing) {
case INTERRUPT_ON_BLOCKING:
if (timing != INTERRUPT_ON_BLOCKING) {
break;
}
/* fall through */
case INTERRUPT_NONE: /* default: IMMEDIATE */
case INTERRUPT_IMMEDIATE:
rb_ary_delete_at(th->pending_interrupt_queue, i);
return err;
case INTERRUPT_NEVER:
break;
}
}
th->pending_interrupt_queue_checked = 1;
return Qundef;
#else
VALUE err = rb_ary_shift(th->pending_interrupt_queue);
if (rb_threadptr_pending_interrupt_empty_p(th)) {
th->pending_interrupt_queue_checked = 1;
}
return err;
#endif
}
static int
threadptr_pending_interrupt_active_p(rb_thread_t *th)
{
/*
* For optimization, we don't check async errinfo queue
* if the queue and the thread interrupt mask were not changed
* since last check.
*/
if (th->pending_interrupt_queue_checked) {
return 0;
}
if (rb_threadptr_pending_interrupt_empty_p(th)) {
return 0;
}
return 1;
}
static int
handle_interrupt_arg_check_i(VALUE key, VALUE val, VALUE args)
{
VALUE *maskp = (VALUE *)args;
if (val != sym_immediate && val != sym_on_blocking && val != sym_never) {
rb_raise(rb_eArgError, "unknown mask signature");
}
if (key == rb_eException && (UNDEF_P(*maskp) || NIL_P(*maskp))) {
*maskp = val;
return ST_CONTINUE;
}
if (RTEST(*maskp)) {
if (!RB_TYPE_P(*maskp, T_HASH)) {
VALUE prev = *maskp;
*maskp = rb_ident_hash_new();
if (SYMBOL_P(prev)) {
rb_hash_aset(*maskp, rb_eException, prev);
}
}
rb_hash_aset(*maskp, key, val);
}
else {
*maskp = Qfalse;
}
return ST_CONTINUE;
}
/*
* call-seq:
* Thread.handle_interrupt(hash) { ... } -> result of the block
*
* Changes asynchronous interrupt timing.
*
* _interrupt_ means asynchronous event and corresponding procedure
* by Thread#raise, Thread#kill, signal trap (not supported yet)
* and main thread termination (if main thread terminates, then all
* other thread will be killed).
*
* The given +hash+ has pairs like <code>ExceptionClass =>
* :TimingSymbol</code>. Where the ExceptionClass is the interrupt handled by
* the given block. The TimingSymbol can be one of the following symbols:
*
* [+:immediate+] Invoke interrupts immediately.
* [+:on_blocking+] Invoke interrupts while _BlockingOperation_.
* [+:never+] Never invoke all interrupts.
*
* _BlockingOperation_ means that the operation will block the calling thread,
* such as read and write. On CRuby implementation, _BlockingOperation_ is any
* operation executed without GVL.
*
* Masked asynchronous interrupts are delayed until they are enabled.
* This method is similar to sigprocmask(3).
*
* === NOTE
*
* Asynchronous interrupts are difficult to use.
*
* If you need to communicate between threads, please consider to use another way such as Queue.
*
* Or use them with deep understanding about this method.
*
* === Usage
*
* In this example, we can guard from Thread#raise exceptions.
*
* Using the +:never+ TimingSymbol the RuntimeError exception will always be
* ignored in the first block of the main thread. In the second
* ::handle_interrupt block we can purposefully handle RuntimeError exceptions.
*
* th = Thread.new do
* Thread.handle_interrupt(RuntimeError => :never) {
* begin
* # You can write resource allocation code safely.
* Thread.handle_interrupt(RuntimeError => :immediate) {
* # ...
* }
* ensure
* # You can write resource deallocation code safely.
* end
* }
* end
* Thread.pass
* # ...
* th.raise "stop"
*
* While we are ignoring the RuntimeError exception, it's safe to write our
* resource allocation code. Then, the ensure block is where we can safely
* deallocate your resources.
*
* ==== Guarding from Timeout::Error
*
* In the next example, we will guard from the Timeout::Error exception. This
* will help prevent from leaking resources when Timeout::Error exceptions occur
* during normal ensure clause. For this example we use the help of the
* standard library Timeout, from lib/timeout.rb
*
* require 'timeout'
* Thread.handle_interrupt(Timeout::Error => :never) {
* timeout(10){
* # Timeout::Error doesn't occur here
* Thread.handle_interrupt(Timeout::Error => :on_blocking) {
* # possible to be killed by Timeout::Error
* # while blocking operation
* }
* # Timeout::Error doesn't occur here
* }
* }
*
* In the first part of the +timeout+ block, we can rely on Timeout::Error being
* ignored. Then in the <code>Timeout::Error => :on_blocking</code> block, any
* operation that will block the calling thread is susceptible to a
* Timeout::Error exception being raised.
*
* ==== Stack control settings
*
* It's possible to stack multiple levels of ::handle_interrupt blocks in order
* to control more than one ExceptionClass and TimingSymbol at a time.
*
* Thread.handle_interrupt(FooError => :never) {
* Thread.handle_interrupt(BarError => :never) {
* # FooError and BarError are prohibited.
* }
* }
*
* ==== Inheritance with ExceptionClass
*
* All exceptions inherited from the ExceptionClass parameter will be considered.
*
* Thread.handle_interrupt(Exception => :never) {
* # all exceptions inherited from Exception are prohibited.
* }
*
* For handling all interrupts, use +Object+ and not +Exception+
* as the ExceptionClass, as kill/terminate interrupts are not handled by +Exception+.
*/
static VALUE
rb_thread_s_handle_interrupt(VALUE self, VALUE mask_arg)
{
VALUE mask = Qundef;
rb_execution_context_t * volatile ec = GET_EC();
rb_thread_t * volatile th = rb_ec_thread_ptr(ec);
volatile VALUE r = Qnil;
enum ruby_tag_type state;
if (!rb_block_given_p()) {
rb_raise(rb_eArgError, "block is needed.");
}
mask_arg = rb_to_hash_type(mask_arg);
if (OBJ_FROZEN(mask_arg) && rb_hash_compare_by_id_p(mask_arg)) {
mask = Qnil;
}
rb_hash_foreach(mask_arg, handle_interrupt_arg_check_i, (VALUE)&mask);
if (UNDEF_P(mask)) {
return rb_yield(Qnil);
}
if (!RTEST(mask)) {
mask = mask_arg;
}
else if (RB_TYPE_P(mask, T_HASH)) {
OBJ_FREEZE_RAW(mask);
}
rb_ary_push(th->pending_interrupt_mask_stack, mask);
if (!rb_threadptr_pending_interrupt_empty_p(th)) {
th->pending_interrupt_queue_checked = 0;
RUBY_VM_SET_INTERRUPT(th->ec);
}
EC_PUSH_TAG(th->ec);
if ((state = EC_EXEC_TAG()) == TAG_NONE) {
r = rb_yield(Qnil);
}
EC_POP_TAG();
rb_ary_pop(th->pending_interrupt_mask_stack);
if (!rb_threadptr_pending_interrupt_empty_p(th)) {
th->pending_interrupt_queue_checked = 0;
RUBY_VM_SET_INTERRUPT(th->ec);
}
RUBY_VM_CHECK_INTS(th->ec);
if (state) {
EC_JUMP_TAG(th->ec, state);
}
return r;
}
/*
* call-seq:
* target_thread.pending_interrupt?(error = nil) -> true/false
*
* Returns whether or not the asynchronous queue is empty for the target thread.
*
* If +error+ is given, then check only for +error+ type deferred events.
*
* See ::pending_interrupt? for more information.
*/
static VALUE
rb_thread_pending_interrupt_p(int argc, VALUE *argv, VALUE target_thread)
{
rb_thread_t *target_th = rb_thread_ptr(target_thread);
if (!target_th->pending_interrupt_queue) {
return Qfalse;
}
if (rb_threadptr_pending_interrupt_empty_p(target_th)) {
return Qfalse;
}
if (rb_check_arity(argc, 0, 1)) {
VALUE err = argv[0];
if (!rb_obj_is_kind_of(err, rb_cModule)) {
rb_raise(rb_eTypeError, "class or module required for rescue clause");
}
return RBOOL(rb_threadptr_pending_interrupt_include_p(target_th, err));
}
else {
return Qtrue;
}
}
/*
* call-seq:
* Thread.pending_interrupt?(error = nil) -> true/false
*
* Returns whether or not the asynchronous queue is empty.
*
* Since Thread::handle_interrupt can be used to defer asynchronous events,
* this method can be used to determine if there are any deferred events.
*
* If you find this method returns true, then you may finish +:never+ blocks.
*
* For example, the following method processes deferred asynchronous events
* immediately.
*
* def Thread.kick_interrupt_immediately
* Thread.handle_interrupt(Object => :immediate) {
* Thread.pass
* }
* end
*
* If +error+ is given, then check only for +error+ type deferred events.
*
* === Usage
*
* th = Thread.new{
* Thread.handle_interrupt(RuntimeError => :on_blocking){
* while true
* ...
* # reach safe point to invoke interrupt
* if Thread.pending_interrupt?
* Thread.handle_interrupt(Object => :immediate){}
* end
* ...
* end
* }
* }
* ...
* th.raise # stop thread
*
* This example can also be written as the following, which you should use to
* avoid asynchronous interrupts.
*
* flag = true
* th = Thread.new{
* Thread.handle_interrupt(RuntimeError => :on_blocking){
* while true
* ...
* # reach safe point to invoke interrupt
* break if flag == false
* ...
* end
* }
* }
* ...
* flag = false # stop thread
*/
static VALUE
rb_thread_s_pending_interrupt_p(int argc, VALUE *argv, VALUE self)
{
return rb_thread_pending_interrupt_p(argc, argv, GET_THREAD()->self);
}
NORETURN(static void rb_threadptr_to_kill(rb_thread_t *th));
static void
rb_threadptr_to_kill(rb_thread_t *th)
{
rb_threadptr_pending_interrupt_clear(th);
th->status = THREAD_RUNNABLE;
th->to_kill = 1;
th->ec->errinfo = INT2FIX(TAG_FATAL);
EC_JUMP_TAG(th->ec, TAG_FATAL);
}
static inline rb_atomic_t
threadptr_get_interrupts(rb_thread_t *th)
{
rb_execution_context_t *ec = th->ec;
rb_atomic_t interrupt;
rb_atomic_t old;
do {
interrupt = ec->interrupt_flag;
old = ATOMIC_CAS(ec->interrupt_flag, interrupt, interrupt & ec->interrupt_mask);
} while (old != interrupt);
return interrupt & (rb_atomic_t)~ec->interrupt_mask;
}
int
rb_threadptr_execute_interrupts(rb_thread_t *th, int blocking_timing)
{
rb_atomic_t interrupt;
int postponed_job_interrupt = 0;
int ret = FALSE;
if (th->ec->raised_flag) return ret;
while ((interrupt = threadptr_get_interrupts(th)) != 0) {
int sig;
int timer_interrupt;
int pending_interrupt;
int trap_interrupt;
int terminate_interrupt;
timer_interrupt = interrupt & TIMER_INTERRUPT_MASK;
pending_interrupt = interrupt & PENDING_INTERRUPT_MASK;
postponed_job_interrupt = interrupt & POSTPONED_JOB_INTERRUPT_MASK;
trap_interrupt = interrupt & TRAP_INTERRUPT_MASK;
terminate_interrupt = interrupt & TERMINATE_INTERRUPT_MASK; // request from other ractors
if (interrupt & VM_BARRIER_INTERRUPT_MASK) {
RB_VM_LOCK_ENTER();
RB_VM_LOCK_LEAVE();
}
if (postponed_job_interrupt) {
rb_postponed_job_flush(th->vm);
}
/* signal handling */
if (trap_interrupt && (th == th->vm->ractor.main_thread)) {
enum rb_thread_status prev_status = th->status;
th->status = THREAD_RUNNABLE;
{
while ((sig = rb_get_next_signal()) != 0) {
ret |= rb_signal_exec(th, sig);
}
}
th->status = prev_status;
}
/* exception from another thread */
if (pending_interrupt && threadptr_pending_interrupt_active_p(th)) {
VALUE err = rb_threadptr_pending_interrupt_deque(th, blocking_timing ? INTERRUPT_ON_BLOCKING : INTERRUPT_NONE);
RUBY_DEBUG_LOG("err:%"PRIdVALUE, err);
ret = TRUE;
if (UNDEF_P(err)) {
/* no error */
}
else if (err == RUBY_FATAL_THREAD_KILLED /* Thread#kill received */ ||
err == RUBY_FATAL_THREAD_TERMINATED /* Terminate thread */ ||
err == INT2FIX(TAG_FATAL) /* Thread.exit etc. */ ) {
terminate_interrupt = 1;
}
else {
if (err == th->vm->special_exceptions[ruby_error_stream_closed]) {
/* the only special exception to be queued across thread */
err = ruby_vm_special_exception_copy(err);
}
/* set runnable if th was slept. */
if (th->status == THREAD_STOPPED ||
th->status == THREAD_STOPPED_FOREVER)
th->status = THREAD_RUNNABLE;
rb_exc_raise(err);
}
}
if (terminate_interrupt) {
rb_threadptr_to_kill(th);
}
if (timer_interrupt) {
uint32_t limits_us = TIME_QUANTUM_USEC;
if (th->priority > 0)
limits_us <<= th->priority;
else
limits_us >>= -th->priority;
if (th->status == THREAD_RUNNABLE)
th->running_time_us += 10 * 1000; // 10ms = 10_000us // TODO: use macro
VM_ASSERT(th->ec->cfp);
EXEC_EVENT_HOOK(th->ec, RUBY_INTERNAL_EVENT_SWITCH, th->ec->cfp->self,
0, 0, 0, Qundef);
rb_thread_schedule_limits(limits_us);
}
}
return ret;
}
void
rb_thread_execute_interrupts(VALUE thval)
{
rb_threadptr_execute_interrupts(rb_thread_ptr(thval), 1);
}
static void
rb_threadptr_ready(rb_thread_t *th)
{
rb_threadptr_interrupt(th);
}
static VALUE
rb_threadptr_raise(rb_thread_t *target_th, int argc, VALUE *argv)
{
VALUE exc;
if (rb_threadptr_dead(target_th)) {
return Qnil;
}
if (argc == 0) {
exc = rb_exc_new(rb_eRuntimeError, 0, 0);
}
else {
exc = rb_make_exception(argc, argv);
}
/* making an exception object can switch thread,
so we need to check thread deadness again */
if (rb_threadptr_dead(target_th)) {
return Qnil;
}
rb_ec_setup_exception(GET_EC(), exc, Qundef);
rb_threadptr_pending_interrupt_enque(target_th, exc);
rb_threadptr_interrupt(target_th);
return Qnil;
}
void
rb_threadptr_signal_raise(rb_thread_t *th, int sig)
{
VALUE argv[2];
argv[0] = rb_eSignal;
argv[1] = INT2FIX(sig);
rb_threadptr_raise(th->vm->ractor.main_thread, 2, argv);
}
void
rb_threadptr_signal_exit(rb_thread_t *th)
{
VALUE argv[2];
argv[0] = rb_eSystemExit;
argv[1] = rb_str_new2("exit");
// TODO: check signal raise deliverly
rb_threadptr_raise(th->vm->ractor.main_thread, 2, argv);
}
int
rb_ec_set_raised(rb_execution_context_t *ec)
{
if (ec->raised_flag & RAISED_EXCEPTION) {
return 1;
}
ec->raised_flag |= RAISED_EXCEPTION;
return 0;
}
int
rb_ec_reset_raised(rb_execution_context_t *ec)
{
if (!(ec->raised_flag & RAISED_EXCEPTION)) {
return 0;
}
ec->raised_flag &= ~RAISED_EXCEPTION;
return 1;
}
int
rb_notify_fd_close(int fd, struct rb_io_close_wait_list *busy)
{
rb_vm_t *vm = GET_THREAD()->vm;
struct waiting_fd *wfd = 0, *next;
ccan_list_head_init(&busy->pending_fd_users);
int has_any;
VALUE wakeup_mutex;
RB_VM_LOCK_ENTER();
{
ccan_list_for_each_safe(&vm->waiting_fds, wfd, next, wfd_node) {
if (wfd->fd == fd) {
rb_thread_t *th = wfd->th;
VALUE err;
ccan_list_del(&wfd->wfd_node);
ccan_list_add(&busy->pending_fd_users, &wfd->wfd_node);
wfd->busy = busy;
err = th->vm->special_exceptions[ruby_error_stream_closed];
rb_threadptr_pending_interrupt_enque(th, err);
rb_threadptr_interrupt(th);
}
}
}
has_any = !ccan_list_empty(&busy->pending_fd_users);
busy->closing_thread = rb_thread_current();
busy->closing_fiber = rb_fiber_current();
wakeup_mutex = Qnil;
if (has_any) {
wakeup_mutex = rb_mutex_new();
RBASIC_CLEAR_CLASS(wakeup_mutex); /* hide from ObjectSpace */
}
busy->wakeup_mutex = wakeup_mutex;
RB_VM_LOCK_LEAVE();
/* If the caller didn't pass *busy as a pointer to something on the stack,
we need to guard this mutex object on _our_ C stack for the duration
of this function. */
RB_GC_GUARD(wakeup_mutex);
return has_any;
}
void
rb_notify_fd_close_wait(struct rb_io_close_wait_list *busy)
{
if (!RB_TEST(busy->wakeup_mutex)) {
/* There was nobody else using this file when we closed it, so we
never bothered to allocate a mutex*/
return;
}
rb_mutex_lock(busy->wakeup_mutex);
while (!ccan_list_empty(&busy->pending_fd_users)) {
rb_mutex_sleep(busy->wakeup_mutex, Qnil);
}
rb_mutex_unlock(busy->wakeup_mutex);
}
void
rb_thread_fd_close(int fd)
{
struct rb_io_close_wait_list busy;
if (rb_notify_fd_close(fd, &busy)) {
rb_notify_fd_close_wait(&busy);
}
}
/*
* call-seq:
* thr.raise
* thr.raise(string)
* thr.raise(exception [, string [, array]])
*
* Raises an exception from the given thread. The caller does not have to be
* +thr+. See Kernel#raise for more information.
*
* Thread.abort_on_exception = true
* a = Thread.new { sleep(200) }
* a.raise("Gotcha")
*
* This will produce:
*
* prog.rb:3: Gotcha (RuntimeError)
* from prog.rb:2:in `initialize'
* from prog.rb:2:in `new'
* from prog.rb:2
*/
static VALUE
thread_raise_m(int argc, VALUE *argv, VALUE self)
{
rb_thread_t *target_th = rb_thread_ptr(self);
const rb_thread_t *current_th = GET_THREAD();
threadptr_check_pending_interrupt_queue(target_th);
rb_threadptr_raise(target_th, argc, argv);
/* To perform Thread.current.raise as Kernel.raise */
if (current_th == target_th) {
RUBY_VM_CHECK_INTS(target_th->ec);
}
return Qnil;
}
/*
* call-seq:
* thr.exit -> thr
* thr.kill -> thr
* thr.terminate -> thr
*
* Terminates +thr+ and schedules another thread to be run, returning
* the terminated Thread. If this is the main thread, or the last
* thread, exits the process.
*/
VALUE
rb_thread_kill(VALUE thread)
{
rb_thread_t *target_th = rb_thread_ptr(thread);
if (target_th->to_kill || target_th->status == THREAD_KILLED) {
return thread;
}
if (target_th == target_th->vm->ractor.main_thread) {
rb_exit(EXIT_SUCCESS);
}
RUBY_DEBUG_LOG("target_th:%u", rb_th_serial(target_th));
if (target_th == GET_THREAD()) {
/* kill myself immediately */
rb_threadptr_to_kill(target_th);
}
else {
threadptr_check_pending_interrupt_queue(target_th);
rb_threadptr_pending_interrupt_enque(target_th, RUBY_FATAL_THREAD_KILLED);
rb_threadptr_interrupt(target_th);
}
return thread;
}
int
rb_thread_to_be_killed(VALUE thread)
{
rb_thread_t *target_th = rb_thread_ptr(thread);
if (target_th->to_kill || target_th->status == THREAD_KILLED) {
return TRUE;
}
return FALSE;
}
/*
* call-seq:
* Thread.kill(thread) -> thread
*
* Causes the given +thread+ to exit, see also Thread::exit.
*
* count = 0
* a = Thread.new { loop { count += 1 } }
* sleep(0.1) #=> 0
* Thread.kill(a) #=> #<Thread:0x401b3d30 dead>
* count #=> 93947
* a.alive? #=> false
*/
static VALUE
rb_thread_s_kill(VALUE obj, VALUE th)
{
return rb_thread_kill(th);
}
/*
* call-seq:
* Thread.exit -> thread
*
* Terminates the currently running thread and schedules another thread to be
* run.
*
* If this thread is already marked to be killed, ::exit returns the Thread.
*
* If this is the main thread, or the last thread, exit the process.
*/
static VALUE
rb_thread_exit(VALUE _)
{
rb_thread_t *th = GET_THREAD();
return rb_thread_kill(th->self);
}
/*
* call-seq:
* thr.wakeup -> thr
*
* Marks a given thread as eligible for scheduling, however it may still
* remain blocked on I/O.
*
* *Note:* This does not invoke the scheduler, see #run for more information.
*
* c = Thread.new { Thread.stop; puts "hey!" }
* sleep 0.1 while c.status!='sleep'
* c.wakeup
* c.join
* #=> "hey!"
*/
VALUE
rb_thread_wakeup(VALUE thread)
{
if (!RTEST(rb_thread_wakeup_alive(thread))) {
rb_raise(rb_eThreadError, "killed thread");
}
return thread;
}
VALUE
rb_thread_wakeup_alive(VALUE thread)
{
rb_thread_t *target_th = rb_thread_ptr(thread);
if (target_th->status == THREAD_KILLED) return Qnil;
rb_threadptr_ready(target_th);
if (target_th->status == THREAD_STOPPED ||
target_th->status == THREAD_STOPPED_FOREVER) {
target_th->status = THREAD_RUNNABLE;
}
return thread;
}
/*
* call-seq:
* thr.run -> thr
*
* Wakes up +thr+, making it eligible for scheduling.
*
* a = Thread.new { puts "a"; Thread.stop; puts "c" }
* sleep 0.1 while a.status!='sleep'
* puts "Got here"
* a.run
* a.join
*
* This will produce:
*
* a
* Got here
* c
*
* See also the instance method #wakeup.
*/
VALUE
rb_thread_run(VALUE thread)
{
rb_thread_wakeup(thread);
rb_thread_schedule();
return thread;
}
VALUE
rb_thread_stop(void)
{
if (rb_thread_alone()) {
rb_raise(rb_eThreadError,
"stopping only thread\n\tnote: use sleep to stop forever");
}
rb_thread_sleep_deadly();
return Qnil;
}
/*
* call-seq:
* Thread.stop -> nil
*
* Stops execution of the current thread, putting it into a ``sleep'' state,
* and schedules execution of another thread.
*
* a = Thread.new { print "a"; Thread.stop; print "c" }
* sleep 0.1 while a.status!='sleep'
* print "b"
* a.run
* a.join
* #=> "abc"
*/
static VALUE
thread_stop(VALUE _)
{
return rb_thread_stop();
}
/********************************************************************/
VALUE
rb_thread_list(void)
{
// TODO
return rb_ractor_thread_list();
}
/*
* call-seq:
* Thread.list -> array
*
* Returns an array of Thread objects for all threads that are either runnable
* or stopped.
*
* Thread.new { sleep(200) }
* Thread.new { 1000000.times {|i| i*i } }
* Thread.new { Thread.stop }
* Thread.list.each {|t| p t}
*
* This will produce:
*
* #<Thread:0x401b3e84 sleep>
* #<Thread:0x401b3f38 run>
* #<Thread:0x401b3fb0 sleep>
* #<Thread:0x401bdf4c run>
*/
static VALUE
thread_list(VALUE _)
{
return rb_thread_list();
}
VALUE
rb_thread_current(void)
{
return GET_THREAD()->self;
}
/*
* call-seq:
* Thread.current -> thread
*
* Returns the currently executing thread.
*
* Thread.current #=> #<Thread:0x401bdf4c run>
*/
static VALUE
thread_s_current(VALUE klass)
{
return rb_thread_current();
}
VALUE
rb_thread_main(void)
{
return GET_RACTOR()->threads.main->self;
}
/*
* call-seq:
* Thread.main -> thread
*
* Returns the main thread.
*/
static VALUE
rb_thread_s_main(VALUE klass)
{
return rb_thread_main();
}
/*
* call-seq:
* Thread.abort_on_exception -> true or false
*
* Returns the status of the global ``abort on exception'' condition.
*
* The default is +false+.
*
* When set to +true+, if any thread is aborted by an exception, the
* raised exception will be re-raised in the main thread.
*
* Can also be specified by the global $DEBUG flag or command line option
* +-d+.
*
* See also ::abort_on_exception=.
*
* There is also an instance level method to set this for a specific thread,
* see #abort_on_exception.
*/
static VALUE
rb_thread_s_abort_exc(VALUE _)
{
return RBOOL(GET_THREAD()->vm->thread_abort_on_exception);
}
/*
* call-seq:
* Thread.abort_on_exception= boolean -> true or false
*
* When set to +true+, if any thread is aborted by an exception, the
* raised exception will be re-raised in the main thread.
* Returns the new state.
*
* Thread.abort_on_exception = true
* t1 = Thread.new do
* puts "In new thread"
* raise "Exception from thread"
* end
* sleep(1)
* puts "not reached"
*
* This will produce:
*
* In new thread
* prog.rb:4: Exception from thread (RuntimeError)
* from prog.rb:2:in `initialize'
* from prog.rb:2:in `new'
* from prog.rb:2
*
* See also ::abort_on_exception.
*
* There is also an instance level method to set this for a specific thread,
* see #abort_on_exception=.
*/
static VALUE
rb_thread_s_abort_exc_set(VALUE self, VALUE val)
{
GET_THREAD()->vm->thread_abort_on_exception = RTEST(val);
return val;
}
/*
* call-seq:
* thr.abort_on_exception -> true or false
*
* Returns the status of the thread-local ``abort on exception'' condition for
* this +thr+.
*
* The default is +false+.
*
* See also #abort_on_exception=.
*
* There is also a class level method to set this for all threads, see
* ::abort_on_exception.
*/
static VALUE
rb_thread_abort_exc(VALUE thread)
{
return RBOOL(rb_thread_ptr(thread)->abort_on_exception);
}
/*
* call-seq:
* thr.abort_on_exception= boolean -> true or false
*
* When set to +true+, if this +thr+ is aborted by an exception, the
* raised exception will be re-raised in the main thread.
*
* See also #abort_on_exception.
*
* There is also a class level method to set this for all threads, see
* ::abort_on_exception=.
*/
static VALUE
rb_thread_abort_exc_set(VALUE thread, VALUE val)
{
rb_thread_ptr(thread)->abort_on_exception = RTEST(val);
return val;
}
/*
* call-seq:
* Thread.report_on_exception -> true or false
*
* Returns the status of the global ``report on exception'' condition.
*
* The default is +true+ since Ruby 2.5.
*
* All threads created when this flag is true will report
* a message on $stderr if an exception kills the thread.
*
* Thread.new { 1.times { raise } }
*
* will produce this output on $stderr:
*
* #<Thread:...> terminated with exception (report_on_exception is true):
* Traceback (most recent call last):
* 2: from -e:1:in `block in <main>'
* 1: from -e:1:in `times'
*
* This is done to catch errors in threads early.
* In some cases, you might not want this output.
* There are multiple ways to avoid the extra output:
*
* * If the exception is not intended, the best is to fix the cause of
* the exception so it does not happen anymore.
* * If the exception is intended, it might be better to rescue it closer to
* where it is raised rather then let it kill the Thread.
* * If it is guaranteed the Thread will be joined with Thread#join or
* Thread#value, then it is safe to disable this report with
* <code>Thread.current.report_on_exception = false</code>
* when starting the Thread.
* However, this might handle the exception much later, or not at all
* if the Thread is never joined due to the parent thread being blocked, etc.
*
* See also ::report_on_exception=.
*
* There is also an instance level method to set this for a specific thread,
* see #report_on_exception=.
*
*/
static VALUE
rb_thread_s_report_exc(VALUE _)
{
return RBOOL(GET_THREAD()->vm->thread_report_on_exception);
}
/*
* call-seq:
* Thread.report_on_exception= boolean -> true or false
*
* Returns the new state.
* When set to +true+, all threads created afterwards will inherit the
* condition and report a message on $stderr if an exception kills a thread:
*
* Thread.report_on_exception = true
* t1 = Thread.new do
* puts "In new thread"
* raise "Exception from thread"
* end
* sleep(1)
* puts "In the main thread"
*
* This will produce:
*
* In new thread
* #<Thread:...prog.rb:2> terminated with exception (report_on_exception is true):
* Traceback (most recent call last):
* prog.rb:4:in `block in <main>': Exception from thread (RuntimeError)
* In the main thread
*
* See also ::report_on_exception.
*
* There is also an instance level method to set this for a specific thread,
* see #report_on_exception=.
*/
static VALUE
rb_thread_s_report_exc_set(VALUE self, VALUE val)
{
GET_THREAD()->vm->thread_report_on_exception = RTEST(val);
return val;
}
/*
* call-seq:
* Thread.ignore_deadlock -> true or false
*
* Returns the status of the global ``ignore deadlock'' condition.
* The default is +false+, so that deadlock conditions are not ignored.
*
* See also ::ignore_deadlock=.
*
*/
static VALUE
rb_thread_s_ignore_deadlock(VALUE _)
{
return RBOOL(GET_THREAD()->vm->thread_ignore_deadlock);
}
/*
* call-seq:
* Thread.ignore_deadlock = boolean -> true or false
*
* Returns the new state.
* When set to +true+, the VM will not check for deadlock conditions.
* It is only useful to set this if your application can break a
* deadlock condition via some other means, such as a signal.
*
* Thread.ignore_deadlock = true
* queue = Thread::Queue.new
*
* trap(:SIGUSR1){queue.push "Received signal"}
*
* # raises fatal error unless ignoring deadlock
* puts queue.pop
*
* See also ::ignore_deadlock.
*/
static VALUE
rb_thread_s_ignore_deadlock_set(VALUE self, VALUE val)
{
GET_THREAD()->vm->thread_ignore_deadlock = RTEST(val);
return val;
}
/*
* call-seq:
* thr.report_on_exception -> true or false
*
* Returns the status of the thread-local ``report on exception'' condition for
* this +thr+.
*
* The default value when creating a Thread is the value of
* the global flag Thread.report_on_exception.
*
* See also #report_on_exception=.
*
* There is also a class level method to set this for all new threads, see
* ::report_on_exception=.
*/
static VALUE
rb_thread_report_exc(VALUE thread)
{
return RBOOL(rb_thread_ptr(thread)->report_on_exception);
}
/*
* call-seq:
* thr.report_on_exception= boolean -> true or false
*
* When set to +true+, a message is printed on $stderr if an exception
* kills this +thr+. See ::report_on_exception for details.
*
* See also #report_on_exception.
*
* There is also a class level method to set this for all new threads, see
* ::report_on_exception=.
*/
static VALUE
rb_thread_report_exc_set(VALUE thread, VALUE val)
{
rb_thread_ptr(thread)->report_on_exception = RTEST(val);
return val;
}
/*
* call-seq:
* thr.group -> thgrp or nil
*
* Returns the ThreadGroup which contains the given thread.
*
* Thread.main.group #=> #<ThreadGroup:0x4029d914>
*/
VALUE
rb_thread_group(VALUE thread)
{
return rb_thread_ptr(thread)->thgroup;
}
static const char *
thread_status_name(rb_thread_t *th, int detail)
{
switch (th->status) {
case THREAD_RUNNABLE:
return th->to_kill ? "aborting" : "run";
case THREAD_STOPPED_FOREVER:
if (detail) return "sleep_forever";
case THREAD_STOPPED:
return "sleep";
case THREAD_KILLED:
return "dead";
default:
return "unknown";
}
}
static int
rb_threadptr_dead(rb_thread_t *th)
{
return th->status == THREAD_KILLED;
}
/*
* call-seq:
* thr.status -> string, false or nil
*
* Returns the status of +thr+.
*
* [<tt>"sleep"</tt>]
* Returned if this thread is sleeping or waiting on I/O
* [<tt>"run"</tt>]
* When this thread is executing
* [<tt>"aborting"</tt>]
* If this thread is aborting
* [+false+]
* When this thread is terminated normally
* [+nil+]
* If terminated with an exception.
*
* a = Thread.new { raise("die now") }
* b = Thread.new { Thread.stop }
* c = Thread.new { Thread.exit }
* d = Thread.new { sleep }
* d.kill #=> #<Thread:0x401b3678 aborting>
* a.status #=> nil
* b.status #=> "sleep"
* c.status #=> false
* d.status #=> "aborting"
* Thread.current.status #=> "run"
*
* See also the instance methods #alive? and #stop?
*/
static VALUE
rb_thread_status(VALUE thread)
{
rb_thread_t *target_th = rb_thread_ptr(thread);
if (rb_threadptr_dead(target_th)) {
if (!NIL_P(target_th->ec->errinfo) &&
!FIXNUM_P(target_th->ec->errinfo)) {
return Qnil;
}
else {
return Qfalse;
}
}
else {
return rb_str_new2(thread_status_name(target_th, FALSE));
}
}
/*
* call-seq:
* thr.alive? -> true or false
*
* Returns +true+ if +thr+ is running or sleeping.
*
* thr = Thread.new { }
* thr.join #=> #<Thread:0x401b3fb0 dead>
* Thread.current.alive? #=> true
* thr.alive? #=> false
*
* See also #stop? and #status.
*/
static VALUE
rb_thread_alive_p(VALUE thread)
{
return RBOOL(!thread_finished(rb_thread_ptr(thread)));
}
/*
* call-seq:
* thr.stop? -> true or false
*
* Returns +true+ if +thr+ is dead or sleeping.
*
* a = Thread.new { Thread.stop }
* b = Thread.current
* a.stop? #=> true
* b.stop? #=> false
*
* See also #alive? and #status.
*/
static VALUE
rb_thread_stop_p(VALUE thread)
{
rb_thread_t *th = rb_thread_ptr(thread);
if (rb_threadptr_dead(th)) {
return Qtrue;
}
return RBOOL(th->status == THREAD_STOPPED || th->status == THREAD_STOPPED_FOREVER);
}
/*
* call-seq:
* thr.name -> string
*
* show the name of the thread.
*/
static VALUE
rb_thread_getname(VALUE thread)
{
return rb_thread_ptr(thread)->name;
}
/*
* call-seq:
* thr.name=(name) -> string
*
* set given name to the ruby thread.
* On some platform, it may set the name to pthread and/or kernel.
*/
static VALUE
rb_thread_setname(VALUE thread, VALUE name)
{
rb_thread_t *target_th = rb_thread_ptr(thread);
if (!NIL_P(name)) {
rb_encoding *enc;
StringValueCStr(name);
enc = rb_enc_get(name);
if (!rb_enc_asciicompat(enc)) {
rb_raise(rb_eArgError, "ASCII incompatible encoding (%s)",
rb_enc_name(enc));
}
name = rb_str_new_frozen(name);
}
target_th->name = name;
if (threadptr_initialized(target_th) && target_th->has_dedicated_nt) {
native_set_another_thread_name(target_th->nt->thread_id, name);
}
return name;
}
#if USE_NATIVE_THREAD_NATIVE_THREAD_ID
/*
* call-seq:
* thr.native_thread_id -> integer
*
* Return the native thread ID which is used by the Ruby thread.
*
* The ID depends on the OS. (not POSIX thread ID returned by pthread_self(3))
* * On Linux it is TID returned by gettid(2).
* * On macOS it is the system-wide unique integral ID of thread returned
* by pthread_threadid_np(3).
* * On FreeBSD it is the unique integral ID of the thread returned by
* pthread_getthreadid_np(3).
* * On Windows it is the thread identifier returned by GetThreadId().
* * On other platforms, it raises NotImplementedError.
*
* NOTE:
* If the thread is not associated yet or already deassociated with a native
* thread, it returns _nil_.
* If the Ruby implementation uses M:N thread model, the ID may change
* depending on the timing.
*/
static VALUE
rb_thread_native_thread_id(VALUE thread)
{
rb_thread_t *target_th = rb_thread_ptr(thread);
if (rb_threadptr_dead(target_th)) return Qnil;
return native_thread_native_thread_id(target_th);
}
#else
# define rb_thread_native_thread_id rb_f_notimplement
#endif
/*
* call-seq:
* thr.to_s -> string
*
* Dump the name, id, and status of _thr_ to a string.
*/
static VALUE
rb_thread_to_s(VALUE thread)
{
VALUE cname = rb_class_path(rb_obj_class(thread));
rb_thread_t *target_th = rb_thread_ptr(thread);
const char *status;
VALUE str, loc;
status = thread_status_name(target_th, TRUE);
str = rb_sprintf("#<%"PRIsVALUE":%p", cname, (void *)thread);
if (!NIL_P(target_th->name)) {
rb_str_catf(str, "@%"PRIsVALUE, target_th->name);
}
if ((loc = threadptr_invoke_proc_location(target_th)) != Qnil) {
rb_str_catf(str, " %"PRIsVALUE":%"PRIsVALUE,
RARRAY_AREF(loc, 0), RARRAY_AREF(loc, 1));
}
rb_str_catf(str, " %s>", status);
return str;
}
/* variables for recursive traversals */
#define recursive_key id__recursive_key__
static VALUE
threadptr_local_aref(rb_thread_t *th, ID id)
{
if (id == recursive_key) {
return th->ec->local_storage_recursive_hash;
}
else {
VALUE val;
struct rb_id_table *local_storage = th->ec->local_storage;
if (local_storage != NULL && rb_id_table_lookup(local_storage, id, &val)) {
return val;
}
else {
return Qnil;
}
}
}
VALUE
rb_thread_local_aref(VALUE thread, ID id)
{
return threadptr_local_aref(rb_thread_ptr(thread), id);
}
/*
* call-seq:
* thr[sym] -> obj or nil
*
* Attribute Reference---Returns the value of a fiber-local variable (current thread's root fiber
* if not explicitly inside a Fiber), using either a symbol or a string name.
* If the specified variable does not exist, returns +nil+.
*
* [
* Thread.new { Thread.current["name"] = "A" },
* Thread.new { Thread.current[:name] = "B" },
* Thread.new { Thread.current["name"] = "C" }
* ].each do |th|
* th.join
* puts "#{th.inspect}: #{th[:name]}"
* end
*
* This will produce:
*
* #<Thread:0x00000002a54220 dead>: A
* #<Thread:0x00000002a541a8 dead>: B
* #<Thread:0x00000002a54130 dead>: C
*
* Thread#[] and Thread#[]= are not thread-local but fiber-local.
* This confusion did not exist in Ruby 1.8 because
* fibers are only available since Ruby 1.9.
* Ruby 1.9 chooses that the methods behaves fiber-local to save
* following idiom for dynamic scope.
*
* def meth(newvalue)
* begin
* oldvalue = Thread.current[:name]
* Thread.current[:name] = newvalue
* yield
* ensure
* Thread.current[:name] = oldvalue
* end
* end
*
* The idiom may not work as dynamic scope if the methods are thread-local
* and a given block switches fiber.
*
* f = Fiber.new {
* meth(1) {
* Fiber.yield
* }
* }
* meth(2) {
* f.resume
* }
* f.resume
* p Thread.current[:name]
* #=> nil if fiber-local
* #=> 2 if thread-local (The value 2 is leaked to outside of meth method.)
*
* For thread-local variables, please see #thread_variable_get and
* #thread_variable_set.
*
*/
static VALUE
rb_thread_aref(VALUE thread, VALUE key)
{
ID id = rb_check_id(&key);
if (!id) return Qnil;
return rb_thread_local_aref(thread, id);
}
/*
* call-seq:
* thr.fetch(sym) -> obj
* thr.fetch(sym) { } -> obj
* thr.fetch(sym, default) -> obj
*
* Returns a fiber-local for the given key. If the key can't be
* found, there are several options: With no other arguments, it will
* raise a KeyError exception; if <i>default</i> is given, then that
* will be returned; if the optional code block is specified, then
* that will be run and its result returned. See Thread#[] and
* Hash#fetch.
*/
static VALUE
rb_thread_fetch(int argc, VALUE *argv, VALUE self)
{
VALUE key, val;
ID id;
rb_thread_t *target_th = rb_thread_ptr(self);
int block_given;
rb_check_arity(argc, 1, 2);
key = argv[0];
block_given = rb_block_given_p();
if (block_given && argc == 2) {
rb_warn("block supersedes default value argument");
}
id = rb_check_id(&key);
if (id == recursive_key) {
return target_th->ec->local_storage_recursive_hash;
}
else if (id && target_th->ec->local_storage &&
rb_id_table_lookup(target_th->ec->local_storage, id, &val)) {
return val;
}
else if (block_given) {
return rb_yield(key);
}
else if (argc == 1) {
rb_key_err_raise(rb_sprintf("key not found: %+"PRIsVALUE, key), self, key);
}
else {
return argv[1];
}
}
static VALUE
threadptr_local_aset(rb_thread_t *th, ID id, VALUE val)
{
if (id == recursive_key) {
th->ec->local_storage_recursive_hash = val;
return val;
}
else {
struct rb_id_table *local_storage = th->ec->local_storage;
if (NIL_P(val)) {
if (!local_storage) return Qnil;
rb_id_table_delete(local_storage, id);
return Qnil;
}
else {
if (local_storage == NULL) {
th->ec->local_storage = local_storage = rb_id_table_create(0);
}
rb_id_table_insert(local_storage, id, val);
return val;
}
}
}
VALUE
rb_thread_local_aset(VALUE thread, ID id, VALUE val)
{
if (OBJ_FROZEN(thread)) {
rb_frozen_error_raise(thread, "can't modify frozen thread locals");
}
return threadptr_local_aset(rb_thread_ptr(thread), id, val);
}
/*
* call-seq:
* thr[sym] = obj -> obj
*
* Attribute Assignment---Sets or creates the value of a fiber-local variable,
* using either a symbol or a string.
*
* See also Thread#[].
*
* For thread-local variables, please see #thread_variable_set and
* #thread_variable_get.
*/
static VALUE
rb_thread_aset(VALUE self, VALUE id, VALUE val)
{
return rb_thread_local_aset(self, rb_to_id(id), val);
}
/*
* call-seq:
* thr.thread_variable_get(key) -> obj or nil
*
* Returns the value of a thread local variable that has been set. Note that
* these are different than fiber local values. For fiber local values,
* please see Thread#[] and Thread#[]=.
*
* Thread local values are carried along with threads, and do not respect
* fibers. For example:
*
* Thread.new {
* Thread.current.thread_variable_set("foo", "bar") # set a thread local
* Thread.current["foo"] = "bar" # set a fiber local
*
* Fiber.new {
* Fiber.yield [
* Thread.current.thread_variable_get("foo"), # get the thread local
* Thread.current["foo"], # get the fiber local
* ]
* }.resume
* }.join.value # => ['bar', nil]
*
* The value "bar" is returned for the thread local, where nil is returned
* for the fiber local. The fiber is executed in the same thread, so the
* thread local values are available.
*/
static VALUE
rb_thread_variable_get(VALUE thread, VALUE key)
{
VALUE locals;
if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
return Qnil;
}
locals = rb_thread_local_storage(thread);
return rb_hash_aref(locals, rb_to_symbol(key));
}
/*
* call-seq:
* thr.thread_variable_set(key, value)
*
* Sets a thread local with +key+ to +value+. Note that these are local to
* threads, and not to fibers. Please see Thread#thread_variable_get and
* Thread#[] for more information.
*/
static VALUE
rb_thread_variable_set(VALUE thread, VALUE key, VALUE val)
{
VALUE locals;
if (OBJ_FROZEN(thread)) {
rb_frozen_error_raise(thread, "can't modify frozen thread locals");
}
locals = rb_thread_local_storage(thread);
return rb_hash_aset(locals, rb_to_symbol(key), val);
}
/*
* call-seq:
* thr.key?(sym) -> true or false
*
* Returns +true+ if the given string (or symbol) exists as a fiber-local
* variable.
*
* me = Thread.current
* me[:oliver] = "a"
* me.key?(:oliver) #=> true
* me.key?(:stanley) #=> false
*/
static VALUE
rb_thread_key_p(VALUE self, VALUE key)
{
VALUE val;
ID id = rb_check_id(&key);
struct rb_id_table *local_storage = rb_thread_ptr(self)->ec->local_storage;
if (!id || local_storage == NULL) {
return Qfalse;
}
return RBOOL(rb_id_table_lookup(local_storage, id, &val));
}
static enum rb_id_table_iterator_result
thread_keys_i(ID key, VALUE value, void *ary)
{
rb_ary_push((VALUE)ary, ID2SYM(key));
return ID_TABLE_CONTINUE;
}
int
rb_thread_alone(void)
{
// TODO
return rb_ractor_living_thread_num(GET_RACTOR()) == 1;
}
/*
* call-seq:
* thr.keys -> array
*
* Returns an array of the names of the fiber-local variables (as Symbols).
*
* thr = Thread.new do
* Thread.current[:cat] = 'meow'
* Thread.current["dog"] = 'woof'
* end
* thr.join #=> #<Thread:0x401b3f10 dead>
* thr.keys #=> [:dog, :cat]
*/
static VALUE
rb_thread_keys(VALUE self)
{
struct rb_id_table *local_storage = rb_thread_ptr(self)->ec->local_storage;
VALUE ary = rb_ary_new();
if (local_storage) {
rb_id_table_foreach(local_storage, thread_keys_i, (void *)ary);
}
return ary;
}
static int
keys_i(VALUE key, VALUE value, VALUE ary)
{
rb_ary_push(ary, key);
return ST_CONTINUE;
}
/*
* call-seq:
* thr.thread_variables -> array
*
* Returns an array of the names of the thread-local variables (as Symbols).
*
* thr = Thread.new do
* Thread.current.thread_variable_set(:cat, 'meow')
* Thread.current.thread_variable_set("dog", 'woof')
* end
* thr.join #=> #<Thread:0x401b3f10 dead>
* thr.thread_variables #=> [:dog, :cat]
*
* Note that these are not fiber local variables. Please see Thread#[] and
* Thread#thread_variable_get for more details.
*/
static VALUE
rb_thread_variables(VALUE thread)
{
VALUE locals;
VALUE ary;
ary = rb_ary_new();
if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
return ary;
}
locals = rb_thread_local_storage(thread);
rb_hash_foreach(locals, keys_i, ary);
return ary;
}
/*
* call-seq:
* thr.thread_variable?(key) -> true or false
*
* Returns +true+ if the given string (or symbol) exists as a thread-local
* variable.
*
* me = Thread.current
* me.thread_variable_set(:oliver, "a")
* me.thread_variable?(:oliver) #=> true
* me.thread_variable?(:stanley) #=> false
*
* Note that these are not fiber local variables. Please see Thread#[] and
* Thread#thread_variable_get for more details.
*/
static VALUE
rb_thread_variable_p(VALUE thread, VALUE key)
{
VALUE locals;
if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
return Qfalse;
}
locals = rb_thread_local_storage(thread);
return RBOOL(rb_hash_lookup(locals, rb_to_symbol(key)) != Qnil);
}
/*
* call-seq:
* thr.priority -> integer
*
* Returns the priority of <i>thr</i>. Default is inherited from the
* current thread which creating the new thread, or zero for the
* initial main thread; higher-priority thread will run more frequently
* than lower-priority threads (but lower-priority threads can also run).
*
* This is just hint for Ruby thread scheduler. It may be ignored on some
* platform.
*
* Thread.current.priority #=> 0
*/
static VALUE
rb_thread_priority(VALUE thread)
{
return INT2NUM(rb_thread_ptr(thread)->priority);
}
/*
* call-seq:
* thr.priority= integer -> thr
*
* Sets the priority of <i>thr</i> to <i>integer</i>. Higher-priority threads
* will run more frequently than lower-priority threads (but lower-priority
* threads can also run).
*
* This is just hint for Ruby thread scheduler. It may be ignored on some
* platform.
*
* count1 = count2 = 0
* a = Thread.new do
* loop { count1 += 1 }
* end
* a.priority = -1
*
* b = Thread.new do
* loop { count2 += 1 }
* end
* b.priority = -2
* sleep 1 #=> 1
* count1 #=> 622504
* count2 #=> 5832
*/
static VALUE
rb_thread_priority_set(VALUE thread, VALUE prio)
{
rb_thread_t *target_th = rb_thread_ptr(thread);
int priority;
#if USE_NATIVE_THREAD_PRIORITY
target_th->priority = NUM2INT(prio);
native_thread_apply_priority(th);
#else
priority = NUM2INT(prio);
if (priority > RUBY_THREAD_PRIORITY_MAX) {
priority = RUBY_THREAD_PRIORITY_MAX;
}
else if (priority < RUBY_THREAD_PRIORITY_MIN) {
priority = RUBY_THREAD_PRIORITY_MIN;
}
target_th->priority = (int8_t)priority;
#endif
return INT2NUM(target_th->priority);
}
/* for IO */
#if defined(NFDBITS) && defined(HAVE_RB_FD_INIT)
/*
* several Unix platforms support file descriptors bigger than FD_SETSIZE
* in select(2) system call.
*
* - Linux 2.2.12 (?)
* - NetBSD 1.2 (src/sys/kern/sys_generic.c:1.25)
* select(2) documents how to allocate fd_set dynamically.
* http://netbsd.gw.com/cgi-bin/man-cgi?select++NetBSD-4.0
* - FreeBSD 2.2 (src/sys/kern/sys_generic.c:1.19)
* - OpenBSD 2.0 (src/sys/kern/sys_generic.c:1.4)
* select(2) documents how to allocate fd_set dynamically.
* http://www.openbsd.org/cgi-bin/man.cgi?query=select&manpath=OpenBSD+4.4
* - Solaris 8 has select_large_fdset
* - Mac OS X 10.7 (Lion)
* select(2) returns EINVAL if nfds is greater than FD_SET_SIZE and
* _DARWIN_UNLIMITED_SELECT (or _DARWIN_C_SOURCE) isn't defined.
* https://developer.apple.com/library/archive/releasenotes/Darwin/SymbolVariantsRelNotes/index.html
*
* When fd_set is not big enough to hold big file descriptors,
* it should be allocated dynamically.
* Note that this assumes fd_set is structured as bitmap.
*
* rb_fd_init allocates the memory.
* rb_fd_term free the memory.
* rb_fd_set may re-allocates bitmap.
*
* So rb_fd_set doesn't reject file descriptors bigger than FD_SETSIZE.
*/
void
rb_fd_init(rb_fdset_t *fds)
{
fds->maxfd = 0;
fds->fdset = ALLOC(fd_set);
FD_ZERO(fds->fdset);
}
void
rb_fd_init_copy(rb_fdset_t *dst, rb_fdset_t *src)
{
size_t size = howmany(rb_fd_max(src), NFDBITS) * sizeof(fd_mask);
if (size < sizeof(fd_set))
size = sizeof(fd_set);
dst->maxfd = src->maxfd;
dst->fdset = xmalloc(size);
memcpy(dst->fdset, src->fdset, size);
}
void
rb_fd_term(rb_fdset_t *fds)
{
xfree(fds->fdset);
fds->maxfd = 0;
fds->fdset = 0;
}
void
rb_fd_zero(rb_fdset_t *fds)
{
if (fds->fdset)
MEMZERO(fds->fdset, fd_mask, howmany(fds->maxfd, NFDBITS));
}
static void
rb_fd_resize(int n, rb_fdset_t *fds)
{
size_t m = howmany(n + 1, NFDBITS) * sizeof(fd_mask);
size_t o = howmany(fds->maxfd, NFDBITS) * sizeof(fd_mask);
if (m < sizeof(fd_set)) m = sizeof(fd_set);
if (o < sizeof(fd_set)) o = sizeof(fd_set);
if (m > o) {
fds->fdset = xrealloc(fds->fdset, m);
memset((char *)fds->fdset + o, 0, m - o);
}
if (n >= fds->maxfd) fds->maxfd = n + 1;
}
void
rb_fd_set(int n, rb_fdset_t *fds)
{
rb_fd_resize(n, fds);
FD_SET(n, fds->fdset);
}
void
rb_fd_clr(int n, rb_fdset_t *fds)
{
if (n >= fds->maxfd) return;
FD_CLR(n, fds->fdset);
}
int
rb_fd_isset(int n, const rb_fdset_t *fds)
{
if (n >= fds->maxfd) return 0;
return FD_ISSET(n, fds->fdset) != 0; /* "!= 0" avoids FreeBSD PR 91421 */
}
void
rb_fd_copy(rb_fdset_t *dst, const fd_set *src, int max)
{
size_t size = howmany(max, NFDBITS) * sizeof(fd_mask);
if (size < sizeof(fd_set)) size = sizeof(fd_set);
dst->maxfd = max;
dst->fdset = xrealloc(dst->fdset, size);
memcpy(dst->fdset, src, size);
}
void
rb_fd_dup(rb_fdset_t *dst, const rb_fdset_t *src)
{
size_t size = howmany(rb_fd_max(src), NFDBITS) * sizeof(fd_mask);
if (size < sizeof(fd_set))
size = sizeof(fd_set);
dst->maxfd = src->maxfd;
dst->fdset = xrealloc(dst->fdset, size);
memcpy(dst->fdset, src->fdset, size);
}
int
rb_fd_select(int n, rb_fdset_t *readfds, rb_fdset_t *writefds, rb_fdset_t *exceptfds, struct timeval *timeout)
{
fd_set *r = NULL, *w = NULL, *e = NULL;
if (readfds) {
rb_fd_resize(n - 1, readfds);
r = rb_fd_ptr(readfds);
}
if (writefds) {
rb_fd_resize(n - 1, writefds);
w = rb_fd_ptr(writefds);
}
if (exceptfds) {
rb_fd_resize(n - 1, exceptfds);
e = rb_fd_ptr(exceptfds);
}
return select(n, r, w, e, timeout);
}
#define rb_fd_no_init(fds) ((void)((fds)->fdset = 0), (void)((fds)->maxfd = 0))
#undef FD_ZERO
#undef FD_SET
#undef FD_CLR
#undef FD_ISSET
#define FD_ZERO(f) rb_fd_zero(f)
#define FD_SET(i, f) rb_fd_set((i), (f))
#define FD_CLR(i, f) rb_fd_clr((i), (f))
#define FD_ISSET(i, f) rb_fd_isset((i), (f))
#elif defined(_WIN32)
void
rb_fd_init(rb_fdset_t *set)
{
set->capa = FD_SETSIZE;
set->fdset = ALLOC(fd_set);
FD_ZERO(set->fdset);
}
void
rb_fd_init_copy(rb_fdset_t *dst, rb_fdset_t *src)
{
rb_fd_init(dst);
rb_fd_dup(dst, src);
}
void
rb_fd_term(rb_fdset_t *set)
{
xfree(set->fdset);
set->fdset = NULL;
set->capa = 0;
}
void
rb_fd_set(int fd, rb_fdset_t *set)
{
unsigned int i;
SOCKET s = rb_w32_get_osfhandle(fd);
for (i = 0; i < set->fdset->fd_count; i++) {
if (set->fdset->fd_array[i] == s) {
return;
}
}
if (set->fdset->fd_count >= (unsigned)set->capa) {
set->capa = (set->fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
set->fdset =
rb_xrealloc_mul_add(
set->fdset, set->capa, sizeof(SOCKET), sizeof(unsigned int));
}
set->fdset->fd_array[set->fdset->fd_count++] = s;
}
#undef FD_ZERO
#undef FD_SET
#undef FD_CLR
#undef FD_ISSET
#define FD_ZERO(f) rb_fd_zero(f)
#define FD_SET(i, f) rb_fd_set((i), (f))
#define FD_CLR(i, f) rb_fd_clr((i), (f))
#define FD_ISSET(i, f) rb_fd_isset((i), (f))
#define rb_fd_no_init(fds) (void)((fds)->fdset = 0)
#endif
#ifndef rb_fd_no_init
#define rb_fd_no_init(fds) (void)(fds)
#endif
static int
wait_retryable(volatile int *result, int errnum, rb_hrtime_t *rel, rb_hrtime_t end)
{
if (*result < 0) {
switch (errnum) {
case EINTR:
#ifdef ERESTART
case ERESTART:
#endif
*result = 0;
if (rel && hrtime_update_expire(rel, end)) {
*rel = 0;
}
return TRUE;
}
return FALSE;
}
else if (*result == 0) {
/* check for spurious wakeup */
if (rel) {
return !hrtime_update_expire(rel, end);
}
return TRUE;
}
return FALSE;
}
struct select_set {
int max;
rb_thread_t *th;
rb_fdset_t *rset;
rb_fdset_t *wset;
rb_fdset_t *eset;
rb_fdset_t orig_rset;
rb_fdset_t orig_wset;
rb_fdset_t orig_eset;
struct timeval *timeout;
};
static VALUE
select_set_free(VALUE p)
{
struct select_set *set = (struct select_set *)p;
rb_fd_term(&set->orig_rset);
rb_fd_term(&set->orig_wset);
rb_fd_term(&set->orig_eset);
return Qfalse;
}
static VALUE
do_select(VALUE p)
{
struct select_set *set = (struct select_set *)p;
volatile int result = 0;
int lerrno;
rb_hrtime_t *to, rel, end = 0;
timeout_prepare(&to, &rel, &end, set->timeout);
volatile rb_hrtime_t endtime = end;
#define restore_fdset(dst, src) \
((dst) ? rb_fd_dup(dst, src) : (void)0)
#define do_select_update() \
(restore_fdset(set->rset, &set->orig_rset), \
restore_fdset(set->wset, &set->orig_wset), \
restore_fdset(set->eset, &set->orig_eset), \
TRUE)
do {
lerrno = 0;
BLOCKING_REGION(set->th, {
struct timeval tv;
if (!RUBY_VM_INTERRUPTED(set->th->ec)) {
result = native_fd_select(set->max,
set->rset, set->wset, set->eset,
rb_hrtime2timeval(&tv, to), set->th);
if (result < 0) lerrno = errno;
}
}, ubf_select, set->th, TRUE);
RUBY_VM_CHECK_INTS_BLOCKING(set->th->ec); /* may raise */
} while (wait_retryable(&result, lerrno, to, endtime) && do_select_update());
if (result < 0) {
errno = lerrno;
}
return (VALUE)result;
}
int
rb_thread_fd_select(int max, rb_fdset_t * read, rb_fdset_t * write, rb_fdset_t * except,
struct timeval *timeout)
{
struct select_set set;
set.th = GET_THREAD();
RUBY_VM_CHECK_INTS_BLOCKING(set.th->ec);
set.max = max;
set.rset = read;
set.wset = write;
set.eset = except;
set.timeout = timeout;
if (!set.rset && !set.wset && !set.eset) {
if (!timeout) {
rb_thread_sleep_forever();
return 0;
}
rb_thread_wait_for(*timeout);
return 0;
}
#define fd_init_copy(f) do { \
if (set.f) { \
rb_fd_resize(set.max - 1, set.f); \
if (&set.orig_##f != set.f) { /* sigwait_fd */ \
rb_fd_init_copy(&set.orig_##f, set.f); \
} \
} \
else { \
rb_fd_no_init(&set.orig_##f); \
} \
} while (0)
fd_init_copy(rset);
fd_init_copy(wset);
fd_init_copy(eset);
#undef fd_init_copy
return (int)rb_ensure(do_select, (VALUE)&set, select_set_free, (VALUE)&set);
}
#ifdef USE_POLL
/* The same with linux kernel. TODO: make platform independent definition. */
#define POLLIN_SET (POLLRDNORM | POLLRDBAND | POLLIN | POLLHUP | POLLERR)
#define POLLOUT_SET (POLLWRBAND | POLLWRNORM | POLLOUT | POLLERR)
#define POLLEX_SET (POLLPRI)
#ifndef POLLERR_SET /* defined for FreeBSD for now */
# define POLLERR_SET (0)
#endif
/*
* returns a mask of events
*/
int
rb_thread_wait_for_single_fd(int fd, int events, struct timeval *timeout)
{
struct pollfd fds[1];
volatile int result = 0;
nfds_t nfds;
struct waiting_fd wfd;
int state;
volatile int lerrno;
rb_execution_context_t *ec = GET_EC();
rb_thread_t *th = rb_ec_thread_ptr(ec);
if (thread_io_wait_events(th, ec, fd, events, timeout, &wfd)) {
return 0; // timeout
}
thread_io_setup_wfd(th, fd, &wfd);
EC_PUSH_TAG(wfd.th->ec);
if ((state = EC_EXEC_TAG()) == TAG_NONE) {
rb_hrtime_t *to, rel, end = 0;
RUBY_VM_CHECK_INTS_BLOCKING(wfd.th->ec);
timeout_prepare(&to, &rel, &end, timeout);
volatile rb_hrtime_t endtime = end;
fds[0].fd = fd;
fds[0].events = (short)events;
fds[0].revents = 0;
do {
nfds = 1;
lerrno = 0;
BLOCKING_REGION(wfd.th, {
struct timespec ts;
if (!RUBY_VM_INTERRUPTED(wfd.th->ec)) {
result = ppoll(fds, nfds, rb_hrtime2timespec(&ts, to), 0);
if (result < 0) lerrno = errno;
}
}, ubf_select, wfd.th, TRUE);
RUBY_VM_CHECK_INTS_BLOCKING(wfd.th->ec);
} while (wait_retryable(&result, lerrno, to, endtime));
}
EC_POP_TAG();
thread_io_wake_pending_closer(&wfd);
if (state) {
EC_JUMP_TAG(wfd.th->ec, state);
}
if (result < 0) {
errno = lerrno;
return -1;
}
if (fds[0].revents & POLLNVAL) {
errno = EBADF;
return -1;
}
/*
* POLLIN, POLLOUT have a different meanings from select(2)'s read/write bit.
* Therefore we need to fix it up.
*/
result = 0;
if (fds[0].revents & POLLIN_SET)
result |= RB_WAITFD_IN;
if (fds[0].revents & POLLOUT_SET)
result |= RB_WAITFD_OUT;
if (fds[0].revents & POLLEX_SET)
result |= RB_WAITFD_PRI;
/* all requested events are ready if there is an error */
if (fds[0].revents & POLLERR_SET)
result |= events;
return result;
}
#else /* ! USE_POLL - implement rb_io_poll_fd() using select() */
struct select_args {
union {
int fd;
int error;
} as;
rb_fdset_t *read;
rb_fdset_t *write;
rb_fdset_t *except;
struct waiting_fd wfd;
struct timeval *tv;
};
static VALUE
select_single(VALUE ptr)
{
struct select_args *args = (struct select_args *)ptr;
int r;
r = rb_thread_fd_select(args->as.fd + 1,
args->read, args->write, args->except, args->tv);
if (r == -1)
args->as.error = errno;
if (r > 0) {
r = 0;
if (args->read && rb_fd_isset(args->as.fd, args->read))
r |= RB_WAITFD_IN;
if (args->write && rb_fd_isset(args->as.fd, args->write))
r |= RB_WAITFD_OUT;
if (args->except && rb_fd_isset(args->as.fd, args->except))
r |= RB_WAITFD_PRI;
}
return (VALUE)r;
}
static VALUE
select_single_cleanup(VALUE ptr)
{
struct select_args *args = (struct select_args *)ptr;
thread_io_wake_pending_closer(&args->wfd);
if (args->read) rb_fd_term(args->read);
if (args->write) rb_fd_term(args->write);
if (args->except) rb_fd_term(args->except);
return (VALUE)-1;
}
static rb_fdset_t *
init_set_fd(int fd, rb_fdset_t *fds)
{
if (fd < 0) {
return 0;
}
rb_fd_init(fds);
rb_fd_set(fd, fds);
return fds;
}
int
rb_thread_wait_for_single_fd(int fd, int events, struct timeval *timeout)
{
rb_fdset_t rfds, wfds, efds;
struct select_args args;
int r;
VALUE ptr = (VALUE)&args;
rb_execution_context_t *ec = GET_EC();
rb_thread_t *th = rb_ec_thread_ptr(ec);
if (thread_io_wait_events(th, ec, fd, events, timeout, &args.wfd)) {
return 0; // timeout
}
args.as.fd = fd;
args.read = (events & RB_WAITFD_IN) ? init_set_fd(fd, &rfds) : NULL;
args.write = (events & RB_WAITFD_OUT) ? init_set_fd(fd, &wfds) : NULL;
args.except = (events & RB_WAITFD_PRI) ? init_set_fd(fd, &efds) : NULL;
args.tv = timeout;
args.wfd.fd = fd;
args.wfd.th = th;
args.wfd.busy = NULL;
RB_VM_LOCK_ENTER();
{
ccan_list_add(&args.wfd.th->vm->waiting_fds, &args.wfd.wfd_node);
}
RB_VM_LOCK_LEAVE();
r = (int)rb_ensure(select_single, ptr, select_single_cleanup, ptr);
if (r == -1)
errno = args.as.error;
return r;
}
#endif /* ! USE_POLL */
/*
* for GC
*/
#ifdef USE_CONSERVATIVE_STACK_END
void
rb_gc_set_stack_end(VALUE **stack_end_p)
{
VALUE stack_end;
*stack_end_p = &stack_end;
}
#endif
/*
*
*/
void
rb_threadptr_check_signal(rb_thread_t *mth)
{
/* mth must be main_thread */
if (rb_signal_buff_size() > 0) {
/* wakeup main thread */
threadptr_trap_interrupt(mth);
}
}
static void
async_bug_fd(const char *mesg, int errno_arg, int fd)
{
char buff[64];
size_t n = strlcpy(buff, mesg, sizeof(buff));
if (n < sizeof(buff)-3) {
ruby_snprintf(buff+n, sizeof(buff)-n, "(%d)", fd);
}
rb_async_bug_errno(buff, errno_arg);
}
/* VM-dependent API is not available for this function */
static int
consume_communication_pipe(int fd)
{
#if USE_EVENTFD
uint64_t buff[1];
#else
/* buffer can be shared because no one refers to them. */
static char buff[1024];
#endif
ssize_t result;
int ret = FALSE; /* for rb_sigwait_sleep */
while (1) {
result = read(fd, buff, sizeof(buff));
#if USE_EVENTFD
RUBY_DEBUG_LOG("resultf:%d buff:%lu", (int)result, (unsigned long)buff[0]);
#else
RUBY_DEBUG_LOG("result:%d", (int)result);
#endif
if (result > 0) {
ret = TRUE;
if (USE_EVENTFD || result < (ssize_t)sizeof(buff)) {
return ret;
}
}
else if (result == 0) {
return ret;
}
else if (result < 0) {
int e = errno;
switch (e) {
case EINTR:
continue; /* retry */
case EAGAIN:
#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
case EWOULDBLOCK:
#endif
return ret;
default:
async_bug_fd("consume_communication_pipe: read", e, fd);
}
}
}
}
void
rb_thread_stop_timer_thread(void)
{
if (TIMER_THREAD_CREATED_P() && native_stop_timer_thread()) {
native_reset_timer_thread();
}
}
void
rb_thread_reset_timer_thread(void)
{
native_reset_timer_thread();
}
void
rb_thread_start_timer_thread(void)
{
system_working = 1;
rb_thread_create_timer_thread();
}
static int
clear_coverage_i(st_data_t key, st_data_t val, st_data_t dummy)
{
int i;
VALUE coverage = (VALUE)val;
VALUE lines = RARRAY_AREF(coverage, COVERAGE_INDEX_LINES);
VALUE branches = RARRAY_AREF(coverage, COVERAGE_INDEX_BRANCHES);
if (lines) {
if (GET_VM()->coverage_mode & COVERAGE_TARGET_ONESHOT_LINES) {
rb_ary_clear(lines);
}
else {
int i;
for (i = 0; i < RARRAY_LEN(lines); i++) {
if (RARRAY_AREF(lines, i) != Qnil)
RARRAY_ASET(lines, i, INT2FIX(0));
}
}
}
if (branches) {
VALUE counters = RARRAY_AREF(branches, 1);
for (i = 0; i < RARRAY_LEN(counters); i++) {
RARRAY_ASET(counters, i, INT2FIX(0));
}
}
return ST_CONTINUE;
}
void
rb_clear_coverages(void)
{
VALUE coverages = rb_get_coverages();
if (RTEST(coverages)) {
rb_hash_foreach(coverages, clear_coverage_i, 0);
}
}
#if defined(HAVE_WORKING_FORK)
static void
rb_thread_atfork_internal(rb_thread_t *th, void (*atfork)(rb_thread_t *, const rb_thread_t *))
{
rb_thread_t *i = 0;
rb_vm_t *vm = th->vm;
rb_ractor_t *r = th->ractor;
vm->ractor.main_ractor = r;
vm->ractor.main_thread = th;
r->threads.main = th;
r->status_ = ractor_created;
thread_sched_atfork(TH_SCHED(th));
ubf_list_atfork();
// OK. Only this thread accesses:
ccan_list_for_each(&vm->ractor.set, r, vmlr_node) {
ccan_list_for_each(&r->threads.set, i, lt_node) {
atfork(i, th);
}
}
rb_vm_living_threads_init(vm);
rb_ractor_atfork(vm, th);
rb_vm_postponed_job_atfork();
/* may be held by RJIT threads in parent */
rb_native_mutex_initialize(&vm->workqueue_lock);
/* may be held by any thread in parent */
rb_native_mutex_initialize(&th->interrupt_lock);
vm->fork_gen++;
rb_ractor_sleeper_threads_clear(th->ractor);
rb_clear_coverages();
// restart timer thread (timer threads access to `vm->waitpid_lock` and so on.
rb_thread_reset_timer_thread();
rb_thread_start_timer_thread();
VM_ASSERT(vm->ractor.blocking_cnt == 0);
VM_ASSERT(vm->ractor.cnt == 1);
}
static void
terminate_atfork_i(rb_thread_t *th, const rb_thread_t *current_th)
{
if (th != current_th) {
rb_mutex_abandon_keeping_mutexes(th);
rb_mutex_abandon_locking_mutex(th);
thread_cleanup_func(th, TRUE);
}
}
void rb_fiber_atfork(rb_thread_t *);
void
rb_thread_atfork(void)
{
rb_thread_t *th = GET_THREAD();
rb_threadptr_pending_interrupt_clear(th);
rb_thread_atfork_internal(th, terminate_atfork_i);
th->join_list = NULL;
rb_fiber_atfork(th);
/* We don't want reproduce CVE-2003-0900. */
rb_reset_random_seed();
}
static void
terminate_atfork_before_exec_i(rb_thread_t *th, const rb_thread_t *current_th)
{
if (th != current_th) {
thread_cleanup_func_before_exec(th);
}
}
void
rb_thread_atfork_before_exec(void)
{
rb_thread_t *th = GET_THREAD();
rb_thread_atfork_internal(th, terminate_atfork_before_exec_i);
}
#else
void
rb_thread_atfork(void)
{
}
void
rb_thread_atfork_before_exec(void)
{
}
#endif
struct thgroup {
int enclosed;
};
static const rb_data_type_t thgroup_data_type = {
"thgroup",
{
0,
RUBY_TYPED_DEFAULT_FREE,
NULL, // No external memory to report
},
0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
};
/*
* Document-class: ThreadGroup
*
* ThreadGroup provides a means of keeping track of a number of threads as a
* group.
*
* A given Thread object can only belong to one ThreadGroup at a time; adding
* a thread to a new group will remove it from any previous group.
*
* Newly created threads belong to the same group as the thread from which they
* were created.
*/
/*
* Document-const: Default
*
* The default ThreadGroup created when Ruby starts; all Threads belong to it
* by default.
*/
static VALUE
thgroup_s_alloc(VALUE klass)
{
VALUE group;
struct thgroup *data;
group = TypedData_Make_Struct(klass, struct thgroup, &thgroup_data_type, data);
data->enclosed = 0;
return group;
}
/*
* call-seq:
* thgrp.list -> array
*
* Returns an array of all existing Thread objects that belong to this group.
*
* ThreadGroup::Default.list #=> [#<Thread:0x401bdf4c run>]
*/
static VALUE
thgroup_list(VALUE group)
{
VALUE ary = rb_ary_new();
rb_thread_t *th = 0;
rb_ractor_t *r = GET_RACTOR();
ccan_list_for_each(&r->threads.set, th, lt_node) {
if (th->thgroup == group) {
rb_ary_push(ary, th->self);
}
}
return ary;
}
/*
* call-seq:
* thgrp.enclose -> thgrp
*
* Prevents threads from being added to or removed from the receiving
* ThreadGroup.
*
* New threads can still be started in an enclosed ThreadGroup.
*
* ThreadGroup::Default.enclose #=> #<ThreadGroup:0x4029d914>
* thr = Thread.new { Thread.stop } #=> #<Thread:0x402a7210 sleep>
* tg = ThreadGroup.new #=> #<ThreadGroup:0x402752d4>
* tg.add thr
* #=> ThreadError: can't move from the enclosed thread group
*/
static VALUE
thgroup_enclose(VALUE group)
{
struct thgroup *data;
TypedData_Get_Struct(group, struct thgroup, &thgroup_data_type, data);
data->enclosed = 1;
return group;
}
/*
* call-seq:
* thgrp.enclosed? -> true or false
*
* Returns +true+ if the +thgrp+ is enclosed. See also ThreadGroup#enclose.
*/
static VALUE
thgroup_enclosed_p(VALUE group)
{
struct thgroup *data;
TypedData_Get_Struct(group, struct thgroup, &thgroup_data_type, data);
return RBOOL(data->enclosed);
}
/*
* call-seq:
* thgrp.add(thread) -> thgrp
*
* Adds the given +thread+ to this group, removing it from any other
* group to which it may have previously been a member.
*
* puts "Initial group is #{ThreadGroup::Default.list}"
* tg = ThreadGroup.new
* t1 = Thread.new { sleep }
* t2 = Thread.new { sleep }
* puts "t1 is #{t1}"
* puts "t2 is #{t2}"
* tg.add(t1)
* puts "Initial group now #{ThreadGroup::Default.list}"
* puts "tg group now #{tg.list}"
*
* This will produce:
*
* Initial group is #<Thread:0x401bdf4c>
* t1 is #<Thread:0x401b3c90>
* t2 is #<Thread:0x401b3c18>
* Initial group now #<Thread:0x401b3c18>#<Thread:0x401bdf4c>
* tg group now #<Thread:0x401b3c90>
*/
static VALUE
thgroup_add(VALUE group, VALUE thread)
{
rb_thread_t *target_th = rb_thread_ptr(thread);
struct thgroup *data;
if (OBJ_FROZEN(group)) {
rb_raise(rb_eThreadError, "can't move to the frozen thread group");
}
TypedData_Get_Struct(group, struct thgroup, &thgroup_data_type, data);
if (data->enclosed) {
rb_raise(rb_eThreadError, "can't move to the enclosed thread group");
}
if (OBJ_FROZEN(target_th->thgroup)) {
rb_raise(rb_eThreadError, "can't move from the frozen thread group");
}
TypedData_Get_Struct(target_th->thgroup, struct thgroup, &thgroup_data_type, data);
if (data->enclosed) {
rb_raise(rb_eThreadError,
"can't move from the enclosed thread group");
}
target_th->thgroup = group;
return group;
}
/*
* Document-class: ThreadShield
*/
static void
thread_shield_mark(void *ptr)
{
rb_gc_mark((VALUE)ptr);
}
static const rb_data_type_t thread_shield_data_type = {
"thread_shield",
{thread_shield_mark, 0, 0,},
0, 0, RUBY_TYPED_FREE_IMMEDIATELY
};
static VALUE
thread_shield_alloc(VALUE klass)
{
return TypedData_Wrap_Struct(klass, &thread_shield_data_type, (void *)mutex_alloc(0));
}
#define GetThreadShieldPtr(obj) ((VALUE)rb_check_typeddata((obj), &thread_shield_data_type))
#define THREAD_SHIELD_WAITING_MASK (((FL_USER19-1)&~(FL_USER0-1))|FL_USER19)
#define THREAD_SHIELD_WAITING_SHIFT (FL_USHIFT)
#define THREAD_SHIELD_WAITING_MAX (THREAD_SHIELD_WAITING_MASK>>THREAD_SHIELD_WAITING_SHIFT)
STATIC_ASSERT(THREAD_SHIELD_WAITING_MAX, THREAD_SHIELD_WAITING_MAX <= UINT_MAX);
static inline unsigned int
rb_thread_shield_waiting(VALUE b)
{
return ((RBASIC(b)->flags&THREAD_SHIELD_WAITING_MASK)>>THREAD_SHIELD_WAITING_SHIFT);
}
static inline void
rb_thread_shield_waiting_inc(VALUE b)
{
unsigned int w = rb_thread_shield_waiting(b);
w++;
if (w > THREAD_SHIELD_WAITING_MAX)
rb_raise(rb_eRuntimeError, "waiting count overflow");
RBASIC(b)->flags &= ~THREAD_SHIELD_WAITING_MASK;
RBASIC(b)->flags |= ((VALUE)w << THREAD_SHIELD_WAITING_SHIFT);
}
static inline void
rb_thread_shield_waiting_dec(VALUE b)
{
unsigned int w = rb_thread_shield_waiting(b);
if (!w) rb_raise(rb_eRuntimeError, "waiting count underflow");
w--;
RBASIC(b)->flags &= ~THREAD_SHIELD_WAITING_MASK;
RBASIC(b)->flags |= ((VALUE)w << THREAD_SHIELD_WAITING_SHIFT);
}
VALUE
rb_thread_shield_new(void)
{
VALUE thread_shield = thread_shield_alloc(rb_cThreadShield);
rb_mutex_lock((VALUE)DATA_PTR(thread_shield));
return thread_shield;
}
bool
rb_thread_shield_owned(VALUE self)
{
VALUE mutex = GetThreadShieldPtr(self);
if (!mutex) return false;
rb_mutex_t *m = mutex_ptr(mutex);
return m->fiber == GET_EC()->fiber_ptr;
}
/*
* Wait a thread shield.
*
* Returns
* true: acquired the thread shield
* false: the thread shield was destroyed and no other threads waiting
* nil: the thread shield was destroyed but still in use
*/
VALUE
rb_thread_shield_wait(VALUE self)
{
VALUE mutex = GetThreadShieldPtr(self);
rb_mutex_t *m;
if (!mutex) return Qfalse;
m = mutex_ptr(mutex);
if (m->fiber == GET_EC()->fiber_ptr) return Qnil;
rb_thread_shield_waiting_inc(self);
rb_mutex_lock(mutex);
rb_thread_shield_waiting_dec(self);
if (DATA_PTR(self)) return Qtrue;
rb_mutex_unlock(mutex);
return rb_thread_shield_waiting(self) > 0 ? Qnil : Qfalse;
}
static VALUE
thread_shield_get_mutex(VALUE self)
{
VALUE mutex = GetThreadShieldPtr(self);
if (!mutex)
rb_raise(rb_eThreadError, "destroyed thread shield - %p", (void *)self);
return mutex;
}
/*
* Release a thread shield, and return true if it has waiting threads.
*/
VALUE
rb_thread_shield_release(VALUE self)
{
VALUE mutex = thread_shield_get_mutex(self);
rb_mutex_unlock(mutex);
return RBOOL(rb_thread_shield_waiting(self) > 0);
}
/*
* Release and destroy a thread shield, and return true if it has waiting threads.
*/
VALUE
rb_thread_shield_destroy(VALUE self)
{
VALUE mutex = thread_shield_get_mutex(self);
DATA_PTR(self) = 0;
rb_mutex_unlock(mutex);
return RBOOL(rb_thread_shield_waiting(self) > 0);
}
static VALUE
threadptr_recursive_hash(rb_thread_t *th)
{
return th->ec->local_storage_recursive_hash;
}
static void
threadptr_recursive_hash_set(rb_thread_t *th, VALUE hash)
{
th->ec->local_storage_recursive_hash = hash;
}
ID rb_frame_last_func(void);
/*
* Returns the current "recursive list" used to detect recursion.
* This list is a hash table, unique for the current thread and for
* the current __callee__.
*/
static VALUE
recursive_list_access(VALUE sym)
{
rb_thread_t *th = GET_THREAD();
VALUE hash = threadptr_recursive_hash(th);
VALUE list;
if (NIL_P(hash) || !RB_TYPE_P(hash, T_HASH)) {
hash = rb_ident_hash_new();
threadptr_recursive_hash_set(th, hash);
list = Qnil;
}
else {
list = rb_hash_aref(hash, sym);
}
if (NIL_P(list) || !RB_TYPE_P(list, T_HASH)) {
list = rb_ident_hash_new();
rb_hash_aset(hash, sym, list);
}
return list;
}
/*
* Returns Qtrue if and only if obj (or the pair <obj, paired_obj>) is already
* in the recursion list.
* Assumes the recursion list is valid.
*/
static VALUE
recursive_check(VALUE list, VALUE obj, VALUE paired_obj_id)
{
#if SIZEOF_LONG == SIZEOF_VOIDP
#define OBJ_ID_EQL(obj_id, other) ((obj_id) == (other))
#elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
#define OBJ_ID_EQL(obj_id, other) (RB_BIGNUM_TYPE_P((obj_id)) ? \
rb_big_eql((obj_id), (other)) : ((obj_id) == (other)))
#endif
VALUE pair_list = rb_hash_lookup2(list, obj, Qundef);
if (UNDEF_P(pair_list))
return Qfalse;
if (paired_obj_id) {
if (!RB_TYPE_P(pair_list, T_HASH)) {
if (!OBJ_ID_EQL(paired_obj_id, pair_list))
return Qfalse;
}
else {
if (NIL_P(rb_hash_lookup(pair_list, paired_obj_id)))
return Qfalse;
}
}
return Qtrue;
}
/*
* Pushes obj (or the pair <obj, paired_obj>) in the recursion list.
* For a single obj, it sets list[obj] to Qtrue.
* For a pair, it sets list[obj] to paired_obj_id if possible,
* otherwise list[obj] becomes a hash like:
* {paired_obj_id_1 => true, paired_obj_id_2 => true, ... }
* Assumes the recursion list is valid.
*/
static void
recursive_push(VALUE list, VALUE obj, VALUE paired_obj)
{
VALUE pair_list;
if (!paired_obj) {
rb_hash_aset(list, obj, Qtrue);
}
else if (UNDEF_P(pair_list = rb_hash_lookup2(list, obj, Qundef))) {
rb_hash_aset(list, obj, paired_obj);
}
else {
if (!RB_TYPE_P(pair_list, T_HASH)){
VALUE other_paired_obj = pair_list;
pair_list = rb_hash_new();
rb_hash_aset(pair_list, other_paired_obj, Qtrue);
rb_hash_aset(list, obj, pair_list);
}
rb_hash_aset(pair_list, paired_obj, Qtrue);
}
}
/*
* Pops obj (or the pair <obj, paired_obj>) from the recursion list.
* For a pair, if list[obj] is a hash, then paired_obj_id is
* removed from the hash and no attempt is made to simplify
* list[obj] from {only_one_paired_id => true} to only_one_paired_id
* Assumes the recursion list is valid.
*/
static int
recursive_pop(VALUE list, VALUE obj, VALUE paired_obj)
{
if (paired_obj) {
VALUE pair_list = rb_hash_lookup2(list, obj, Qundef);
if (UNDEF_P(pair_list)) {
return 0;
}
if (RB_TYPE_P(pair_list, T_HASH)) {
rb_hash_delete_entry(pair_list, paired_obj);
if (!RHASH_EMPTY_P(pair_list)) {
return 1; /* keep hash until is empty */
}
}
}
rb_hash_delete_entry(list, obj);
return 1;
}
struct exec_recursive_params {
VALUE (*func) (VALUE, VALUE, int);
VALUE list;
VALUE obj;
VALUE pairid;
VALUE arg;
};
static VALUE
exec_recursive_i(RB_BLOCK_CALL_FUNC_ARGLIST(tag, data))
{
struct exec_recursive_params *p = (void *)data;
return (*p->func)(p->obj, p->arg, FALSE);
}
/*
* Calls func(obj, arg, recursive), where recursive is non-zero if the
* current method is called recursively on obj, or on the pair <obj, pairid>
* If outer is 0, then the innermost func will be called with recursive set
* to Qtrue, otherwise the outermost func will be called. In the latter case,
* all inner func are short-circuited by throw.
* Implementation details: the value thrown is the recursive list which is
* proper to the current method and unlikely to be caught anywhere else.
* list[recursive_key] is used as a flag for the outermost call.
*/
static VALUE
exec_recursive(VALUE (*func) (VALUE, VALUE, int), VALUE obj, VALUE pairid, VALUE arg, int outer, ID mid)
{
VALUE result = Qundef;
const VALUE sym = mid ? ID2SYM(mid) : ID2SYM(idNULL);
struct exec_recursive_params p;
int outermost;
p.list = recursive_list_access(sym);
p.obj = obj;
p.pairid = pairid;
p.arg = arg;
outermost = outer && !recursive_check(p.list, ID2SYM(recursive_key), 0);
if (recursive_check(p.list, p.obj, pairid)) {
if (outer && !outermost) {
rb_throw_obj(p.list, p.list);
}
return (*func)(obj, arg, TRUE);
}
else {
enum ruby_tag_type state;
p.func = func;
if (outermost) {
recursive_push(p.list, ID2SYM(recursive_key), 0);
recursive_push(p.list, p.obj, p.pairid);
result = rb_catch_protect(p.list, exec_recursive_i, (VALUE)&p, &state);
if (!recursive_pop(p.list, p.obj, p.pairid)) goto invalid;
if (!recursive_pop(p.list, ID2SYM(recursive_key), 0)) goto invalid;
if (state != TAG_NONE) EC_JUMP_TAG(GET_EC(), state);
if (result == p.list) {
result = (*func)(obj, arg, TRUE);
}
}
else {
volatile VALUE ret = Qundef;
recursive_push(p.list, p.obj, p.pairid);
EC_PUSH_TAG(GET_EC());
if ((state = EC_EXEC_TAG()) == TAG_NONE) {
ret = (*func)(obj, arg, FALSE);
}
EC_POP_TAG();
if (!recursive_pop(p.list, p.obj, p.pairid)) {
goto invalid;
}
if (state != TAG_NONE) EC_JUMP_TAG(GET_EC(), state);
result = ret;
}
}
*(volatile struct exec_recursive_params *)&p;
return result;
invalid:
rb_raise(rb_eTypeError, "invalid inspect_tbl pair_list "
"for %+"PRIsVALUE" in %+"PRIsVALUE,
sym, rb_thread_current());
UNREACHABLE_RETURN(Qundef);
}
/*
* Calls func(obj, arg, recursive), where recursive is non-zero if the
* current method is called recursively on obj
*/
VALUE
rb_exec_recursive(VALUE (*func) (VALUE, VALUE, int), VALUE obj, VALUE arg)
{
return exec_recursive(func, obj, 0, arg, 0, rb_frame_last_func());
}
/*
* Calls func(obj, arg, recursive), where recursive is non-zero if the
* current method is called recursively on the ordered pair <obj, paired_obj>
*/
VALUE
rb_exec_recursive_paired(VALUE (*func) (VALUE, VALUE, int), VALUE obj, VALUE paired_obj, VALUE arg)
{
return exec_recursive(func, obj, rb_memory_id(paired_obj), arg, 0, rb_frame_last_func());
}
/*
* If recursion is detected on the current method and obj, the outermost
* func will be called with (obj, arg, Qtrue). All inner func will be
* short-circuited using throw.
*/
VALUE
rb_exec_recursive_outer(VALUE (*func) (VALUE, VALUE, int), VALUE obj, VALUE arg)
{
return exec_recursive(func, obj, 0, arg, 1, rb_frame_last_func());
}
VALUE
rb_exec_recursive_outer_mid(VALUE (*func) (VALUE, VALUE, int), VALUE obj, VALUE arg, ID mid)
{
return exec_recursive(func, obj, 0, arg, 1, mid);
}
/*
* If recursion is detected on the current method, obj and paired_obj,
* the outermost func will be called with (obj, arg, Qtrue). All inner
* func will be short-circuited using throw.
*/
VALUE
rb_exec_recursive_paired_outer(VALUE (*func) (VALUE, VALUE, int), VALUE obj, VALUE paired_obj, VALUE arg)
{
return exec_recursive(func, obj, rb_memory_id(paired_obj), arg, 1, rb_frame_last_func());
}
/*
* call-seq:
* thread.backtrace -> array or nil
*
* Returns the current backtrace of the target thread.
*
*/
static VALUE
rb_thread_backtrace_m(int argc, VALUE *argv, VALUE thval)
{
return rb_vm_thread_backtrace(argc, argv, thval);
}
/* call-seq:
* thread.backtrace_locations(*args) -> array or nil
*
* Returns the execution stack for the target thread---an array containing
* backtrace location objects.
*
* See Thread::Backtrace::Location for more information.
*
* This method behaves similarly to Kernel#caller_locations except it applies
* to a specific thread.
*/
static VALUE
rb_thread_backtrace_locations_m(int argc, VALUE *argv, VALUE thval)
{
return rb_vm_thread_backtrace_locations(argc, argv, thval);
}
void
Init_Thread_Mutex(void)
{
rb_thread_t *th = GET_THREAD();
rb_native_mutex_initialize(&th->vm->workqueue_lock);
rb_native_mutex_initialize(&th->interrupt_lock);
}
/*
* Document-class: ThreadError
*
* Raised when an invalid operation is attempted on a thread.
*
* For example, when no other thread has been started:
*
* Thread.stop
*
* This will raises the following exception:
*
* ThreadError: stopping only thread
* note: use sleep to stop forever
*/
void
Init_Thread(void)
{
VALUE cThGroup;
rb_thread_t *th = GET_THREAD();
sym_never = ID2SYM(rb_intern_const("never"));
sym_immediate = ID2SYM(rb_intern_const("immediate"));
sym_on_blocking = ID2SYM(rb_intern_const("on_blocking"));
rb_define_singleton_method(rb_cThread, "new", thread_s_new, -1);
rb_define_singleton_method(rb_cThread, "start", thread_start, -2);
rb_define_singleton_method(rb_cThread, "fork", thread_start, -2);
rb_define_singleton_method(rb_cThread, "main", rb_thread_s_main, 0);
rb_define_singleton_method(rb_cThread, "current", thread_s_current, 0);
rb_define_singleton_method(rb_cThread, "stop", thread_stop, 0);
rb_define_singleton_method(rb_cThread, "kill", rb_thread_s_kill, 1);
rb_define_singleton_method(rb_cThread, "exit", rb_thread_exit, 0);
rb_define_singleton_method(rb_cThread, "pass", thread_s_pass, 0);
rb_define_singleton_method(rb_cThread, "list", thread_list, 0);
rb_define_singleton_method(rb_cThread, "abort_on_exception", rb_thread_s_abort_exc, 0);
rb_define_singleton_method(rb_cThread, "abort_on_exception=", rb_thread_s_abort_exc_set, 1);
rb_define_singleton_method(rb_cThread, "report_on_exception", rb_thread_s_report_exc, 0);
rb_define_singleton_method(rb_cThread, "report_on_exception=", rb_thread_s_report_exc_set, 1);
rb_define_singleton_method(rb_cThread, "ignore_deadlock", rb_thread_s_ignore_deadlock, 0);
rb_define_singleton_method(rb_cThread, "ignore_deadlock=", rb_thread_s_ignore_deadlock_set, 1);
rb_define_singleton_method(rb_cThread, "handle_interrupt", rb_thread_s_handle_interrupt, 1);
rb_define_singleton_method(rb_cThread, "pending_interrupt?", rb_thread_s_pending_interrupt_p, -1);
rb_define_method(rb_cThread, "pending_interrupt?", rb_thread_pending_interrupt_p, -1);
rb_define_method(rb_cThread, "initialize", thread_initialize, -2);
rb_define_method(rb_cThread, "raise", thread_raise_m, -1);
rb_define_method(rb_cThread, "join", thread_join_m, -1);
rb_define_method(rb_cThread, "value", thread_value, 0);
rb_define_method(rb_cThread, "kill", rb_thread_kill, 0);
rb_define_method(rb_cThread, "terminate", rb_thread_kill, 0);
rb_define_method(rb_cThread, "exit", rb_thread_kill, 0);
rb_define_method(rb_cThread, "run", rb_thread_run, 0);
rb_define_method(rb_cThread, "wakeup", rb_thread_wakeup, 0);
rb_define_method(rb_cThread, "[]", rb_thread_aref, 1);
rb_define_method(rb_cThread, "[]=", rb_thread_aset, 2);
rb_define_method(rb_cThread, "fetch", rb_thread_fetch, -1);
rb_define_method(rb_cThread, "key?", rb_thread_key_p, 1);
rb_define_method(rb_cThread, "keys", rb_thread_keys, 0);
rb_define_method(rb_cThread, "priority", rb_thread_priority, 0);
rb_define_method(rb_cThread, "priority=", rb_thread_priority_set, 1);
rb_define_method(rb_cThread, "status", rb_thread_status, 0);
rb_define_method(rb_cThread, "thread_variable_get", rb_thread_variable_get, 1);
rb_define_method(rb_cThread, "thread_variable_set", rb_thread_variable_set, 2);
rb_define_method(rb_cThread, "thread_variables", rb_thread_variables, 0);
rb_define_method(rb_cThread, "thread_variable?", rb_thread_variable_p, 1);
rb_define_method(rb_cThread, "alive?", rb_thread_alive_p, 0);
rb_define_method(rb_cThread, "stop?", rb_thread_stop_p, 0);
rb_define_method(rb_cThread, "abort_on_exception", rb_thread_abort_exc, 0);
rb_define_method(rb_cThread, "abort_on_exception=", rb_thread_abort_exc_set, 1);
rb_define_method(rb_cThread, "report_on_exception", rb_thread_report_exc, 0);
rb_define_method(rb_cThread, "report_on_exception=", rb_thread_report_exc_set, 1);
rb_define_method(rb_cThread, "group", rb_thread_group, 0);
rb_define_method(rb_cThread, "backtrace", rb_thread_backtrace_m, -1);
rb_define_method(rb_cThread, "backtrace_locations", rb_thread_backtrace_locations_m, -1);
rb_define_method(rb_cThread, "name", rb_thread_getname, 0);
rb_define_method(rb_cThread, "name=", rb_thread_setname, 1);
rb_define_method(rb_cThread, "native_thread_id", rb_thread_native_thread_id, 0);
rb_define_method(rb_cThread, "to_s", rb_thread_to_s, 0);
rb_define_alias(rb_cThread, "inspect", "to_s");
rb_vm_register_special_exception(ruby_error_stream_closed, rb_eIOError,
"stream closed in another thread");
cThGroup = rb_define_class("ThreadGroup", rb_cObject);
rb_define_alloc_func(cThGroup, thgroup_s_alloc);
rb_define_method(cThGroup, "list", thgroup_list, 0);
rb_define_method(cThGroup, "enclose", thgroup_enclose, 0);
rb_define_method(cThGroup, "enclosed?", thgroup_enclosed_p, 0);
rb_define_method(cThGroup, "add", thgroup_add, 1);
{
th->thgroup = th->ractor->thgroup_default = rb_obj_alloc(cThGroup);
rb_define_const(cThGroup, "Default", th->thgroup);
}
rb_eThreadError = rb_define_class("ThreadError", rb_eStandardError);
/* init thread core */
{
/* main thread setting */
{
/* acquire global vm lock */
#ifdef HAVE_PTHREAD_NP_H
VM_ASSERT(TH_SCHED(th)->running == th);
#endif
// thread_sched_to_running() should not be called because
// it assumes blocked by thread_sched_to_waiting().
// thread_sched_to_running(sched, th);
th->pending_interrupt_queue = rb_ary_hidden_new(0);
th->pending_interrupt_queue_checked = 0;
th->pending_interrupt_mask_stack = rb_ary_hidden_new(0);
}
}
rb_thread_create_timer_thread();
Init_thread_sync();
// TODO: Suppress unused function warning for now
// if (0) rb_thread_sched_destroy(NULL);
}
int
ruby_native_thread_p(void)
{
rb_thread_t *th = ruby_thread_from_native();
return th != 0;
}
#ifdef NON_SCALAR_THREAD_ID
#define thread_id_str(th) (NULL)
#else
#define thread_id_str(th) ((void *)(uintptr_t)(th)->nt->thread_id)
#endif
static void
debug_deadlock_check(rb_ractor_t *r, VALUE msg)
{
rb_thread_t *th = 0;
VALUE sep = rb_str_new_cstr("\n ");
rb_str_catf(msg, "\n%d threads, %d sleeps current:%p main thread:%p\n",
rb_ractor_living_thread_num(r), rb_ractor_sleeper_thread_num(r),
(void *)GET_THREAD(), (void *)r->threads.main);
ccan_list_for_each(&r->threads.set, th, lt_node) {
rb_str_catf(msg, "* %+"PRIsVALUE"\n rb_thread_t:%p "
"native:%p int:%u",
th->self, (void *)th, th->nt ? thread_id_str(th) : "N/A", th->ec->interrupt_flag);
if (th->locking_mutex) {
rb_mutex_t *mutex = mutex_ptr(th->locking_mutex);
rb_str_catf(msg, " mutex:%p cond:%"PRIuSIZE,
(void *)mutex->fiber, rb_mutex_num_waiting(mutex));
}
{
struct rb_waiting_list *list = th->join_list;
while (list) {
rb_str_catf(msg, "\n depended by: tb_thread_id:%p", (void *)list->thread);
list = list->next;
}
}
rb_str_catf(msg, "\n ");
rb_str_concat(msg, rb_ary_join(rb_ec_backtrace_str_ary(th->ec, 0, 0), sep));
rb_str_catf(msg, "\n");
}
}
static void
rb_check_deadlock(rb_ractor_t *r)
{
if (GET_THREAD()->vm->thread_ignore_deadlock) return;
#ifdef RUBY_THREAD_PTHREAD_H
if (r->threads.sched.readyq_cnt > 0) return;
#endif
int sleeper_num = rb_ractor_sleeper_thread_num(r);
int ltnum = rb_ractor_living_thread_num(r);
if (ltnum > sleeper_num) return;
if (ltnum < sleeper_num) rb_bug("sleeper must not be more than vm_living_thread_num(vm)");
int found = 0;
rb_thread_t *th = NULL;
ccan_list_for_each(&r->threads.set, th, lt_node) {
if (th->status != THREAD_STOPPED_FOREVER || RUBY_VM_INTERRUPTED(th->ec)) {
found = 1;
}
else if (th->locking_mutex) {
rb_mutex_t *mutex = mutex_ptr(th->locking_mutex);
if (mutex->fiber == th->ec->fiber_ptr || (!mutex->fiber && !ccan_list_empty(&mutex->waitq))) {
found = 1;
}
}
if (found)
break;
}
if (!found) {
VALUE argv[2];
argv[0] = rb_eFatal;
argv[1] = rb_str_new2("No live threads left. Deadlock?");
debug_deadlock_check(r, argv[1]);
rb_ractor_sleeper_threads_dec(GET_RACTOR());
rb_threadptr_raise(r->threads.main, 2, argv);
}
}
// Used for VM memsize reporting. Returns the size of a list of waiting_fd
// structs. Defined here because the struct definition lives here as well.
size_t
rb_vm_memsize_waiting_fds(struct ccan_list_head *waiting_fds)
{
struct waiting_fd *waitfd = 0;
size_t size = 0;
ccan_list_for_each(waiting_fds, waitfd, wfd_node) {
size += sizeof(struct waiting_fd);
}
return size;
}
static void
update_line_coverage(VALUE data, const rb_trace_arg_t *trace_arg)
{
const rb_control_frame_t *cfp = GET_EC()->cfp;
VALUE coverage = rb_iseq_coverage(cfp->iseq);
if (RB_TYPE_P(coverage, T_ARRAY) && !RBASIC_CLASS(coverage)) {
VALUE lines = RARRAY_AREF(coverage, COVERAGE_INDEX_LINES);
if (lines) {
long line = rb_sourceline() - 1;
long count;
VALUE num;
void rb_iseq_clear_event_flags(const rb_iseq_t *iseq, size_t pos, rb_event_flag_t reset);
if (GET_VM()->coverage_mode & COVERAGE_TARGET_ONESHOT_LINES) {
rb_iseq_clear_event_flags(cfp->iseq, cfp->pc - ISEQ_BODY(cfp->iseq)->iseq_encoded - 1, RUBY_EVENT_COVERAGE_LINE);
rb_ary_push(lines, LONG2FIX(line + 1));
return;
}
if (line >= RARRAY_LEN(lines)) { /* no longer tracked */
return;
}
num = RARRAY_AREF(lines, line);
if (!FIXNUM_P(num)) return;
count = FIX2LONG(num) + 1;
if (POSFIXABLE(count)) {
RARRAY_ASET(lines, line, LONG2FIX(count));
}
}
}
}
static void
update_branch_coverage(VALUE data, const rb_trace_arg_t *trace_arg)
{
const rb_control_frame_t *cfp = GET_EC()->cfp;
VALUE coverage = rb_iseq_coverage(cfp->iseq);
if (RB_TYPE_P(coverage, T_ARRAY) && !RBASIC_CLASS(coverage)) {
VALUE branches = RARRAY_AREF(coverage, COVERAGE_INDEX_BRANCHES);
if (branches) {
long pc = cfp->pc - ISEQ_BODY(cfp->iseq)->iseq_encoded - 1;
long idx = FIX2INT(RARRAY_AREF(ISEQ_PC2BRANCHINDEX(cfp->iseq), pc)), count;
VALUE counters = RARRAY_AREF(branches, 1);
VALUE num = RARRAY_AREF(counters, idx);
count = FIX2LONG(num) + 1;
if (POSFIXABLE(count)) {
RARRAY_ASET(counters, idx, LONG2FIX(count));
}
}
}
}
const rb_method_entry_t *
rb_resolve_me_location(const rb_method_entry_t *me, VALUE resolved_location[5])
{
VALUE path, beg_pos_lineno, beg_pos_column, end_pos_lineno, end_pos_column;
if (!me->def) return NULL; // negative cme
retry:
switch (me->def->type) {
case VM_METHOD_TYPE_ISEQ: {
const rb_iseq_t *iseq = me->def->body.iseq.iseqptr;
rb_iseq_location_t *loc = &ISEQ_BODY(iseq)->location;
path = rb_iseq_path(iseq);
beg_pos_lineno = INT2FIX(loc->code_location.beg_pos.lineno);
beg_pos_column = INT2FIX(loc->code_location.beg_pos.column);
end_pos_lineno = INT2FIX(loc->code_location.end_pos.lineno);
end_pos_column = INT2FIX(loc->code_location.end_pos.column);
break;
}
case VM_METHOD_TYPE_BMETHOD: {
const rb_iseq_t *iseq = rb_proc_get_iseq(me->def->body.bmethod.proc, 0);
if (iseq) {
rb_iseq_location_t *loc;
rb_iseq_check(iseq);
path = rb_iseq_path(iseq);
loc = &ISEQ_BODY(iseq)->location;
beg_pos_lineno = INT2FIX(loc->code_location.beg_pos.lineno);
beg_pos_column = INT2FIX(loc->code_location.beg_pos.column);
end_pos_lineno = INT2FIX(loc->code_location.end_pos.lineno);
end_pos_column = INT2FIX(loc->code_location.end_pos.column);
break;
}
return NULL;
}
case VM_METHOD_TYPE_ALIAS:
me = me->def->body.alias.original_me;
goto retry;
case VM_METHOD_TYPE_REFINED:
me = me->def->body.refined.orig_me;
if (!me) return NULL;
goto retry;
default:
return NULL;
}
/* found */
if (RB_TYPE_P(path, T_ARRAY)) {
path = rb_ary_entry(path, 1);
if (!RB_TYPE_P(path, T_STRING)) return NULL; /* just for the case... */
}
if (resolved_location) {
resolved_location[0] = path;
resolved_location[1] = beg_pos_lineno;
resolved_location[2] = beg_pos_column;
resolved_location[3] = end_pos_lineno;
resolved_location[4] = end_pos_column;
}
return me;
}
static void
update_method_coverage(VALUE me2counter, rb_trace_arg_t *trace_arg)
{
const rb_control_frame_t *cfp = GET_EC()->cfp;
const rb_callable_method_entry_t *cme = rb_vm_frame_method_entry(cfp);
const rb_method_entry_t *me = (const rb_method_entry_t *)cme;
VALUE rcount;
long count;
me = rb_resolve_me_location(me, 0);
if (!me) return;
rcount = rb_hash_aref(me2counter, (VALUE) me);
count = FIXNUM_P(rcount) ? FIX2LONG(rcount) + 1 : 1;
if (POSFIXABLE(count)) {
rb_hash_aset(me2counter, (VALUE) me, LONG2FIX(count));
}
}
VALUE
rb_get_coverages(void)
{
return GET_VM()->coverages;
}
int
rb_get_coverage_mode(void)
{
return GET_VM()->coverage_mode;
}
void
rb_set_coverages(VALUE coverages, int mode, VALUE me2counter)
{
GET_VM()->coverages = coverages;
GET_VM()->me2counter = me2counter;
GET_VM()->coverage_mode = mode;
}
void
rb_resume_coverages(void)
{
int mode = GET_VM()->coverage_mode;
VALUE me2counter = GET_VM()->me2counter;
rb_add_event_hook2((rb_event_hook_func_t) update_line_coverage, RUBY_EVENT_COVERAGE_LINE, Qnil, RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG);
if (mode & COVERAGE_TARGET_BRANCHES) {
rb_add_event_hook2((rb_event_hook_func_t) update_branch_coverage, RUBY_EVENT_COVERAGE_BRANCH, Qnil, RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG);
}
if (mode & COVERAGE_TARGET_METHODS) {
rb_add_event_hook2((rb_event_hook_func_t) update_method_coverage, RUBY_EVENT_CALL, me2counter, RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG);
}
}
void
rb_suspend_coverages(void)
{
rb_remove_event_hook((rb_event_hook_func_t) update_line_coverage);
if (GET_VM()->coverage_mode & COVERAGE_TARGET_BRANCHES) {
rb_remove_event_hook((rb_event_hook_func_t) update_branch_coverage);
}
if (GET_VM()->coverage_mode & COVERAGE_TARGET_METHODS) {
rb_remove_event_hook((rb_event_hook_func_t) update_method_coverage);
}
}
/* Make coverage arrays empty so old covered files are no longer tracked. */
void
rb_reset_coverages(void)
{
rb_clear_coverages();
rb_iseq_remove_coverage_all();
GET_VM()->coverages = Qfalse;
}
VALUE
rb_default_coverage(int n)
{
VALUE coverage = rb_ary_hidden_new_fill(3);
VALUE lines = Qfalse, branches = Qfalse;
int mode = GET_VM()->coverage_mode;
if (mode & COVERAGE_TARGET_LINES) {
lines = n > 0 ? rb_ary_hidden_new_fill(n) : rb_ary_hidden_new(0);
}
RARRAY_ASET(coverage, COVERAGE_INDEX_LINES, lines);
if (mode & COVERAGE_TARGET_BRANCHES) {
branches = rb_ary_hidden_new_fill(2);
/* internal data structures for branch coverage:
*
* { branch base node =>
* [base_type, base_first_lineno, base_first_column, base_last_lineno, base_last_column, {
* branch target id =>
* [target_type, target_first_lineno, target_first_column, target_last_lineno, target_last_column, target_counter_index],
* ...
* }],
* ...
* }
*
* Example:
* { NODE_CASE =>
* [1, 0, 4, 3, {
* NODE_WHEN => [2, 8, 2, 9, 0],
* NODE_WHEN => [3, 8, 3, 9, 1],
* ...
* }],
* ...
* }
*/
VALUE structure = rb_hash_new();
rb_obj_hide(structure);
RARRAY_ASET(branches, 0, structure);
/* branch execution counters */
RARRAY_ASET(branches, 1, rb_ary_hidden_new(0));
}
RARRAY_ASET(coverage, COVERAGE_INDEX_BRANCHES, branches);
return coverage;
}
static VALUE
uninterruptible_exit(VALUE v)
{
rb_thread_t *cur_th = GET_THREAD();
rb_ary_pop(cur_th->pending_interrupt_mask_stack);
cur_th->pending_interrupt_queue_checked = 0;
if (!rb_threadptr_pending_interrupt_empty_p(cur_th)) {
RUBY_VM_SET_INTERRUPT(cur_th->ec);
}
return Qnil;
}
VALUE
rb_uninterruptible(VALUE (*b_proc)(VALUE), VALUE data)
{
VALUE interrupt_mask = rb_ident_hash_new();
rb_thread_t *cur_th = GET_THREAD();
rb_hash_aset(interrupt_mask, rb_cObject, sym_never);
OBJ_FREEZE_RAW(interrupt_mask);
rb_ary_push(cur_th->pending_interrupt_mask_stack, interrupt_mask);
VALUE ret = rb_ensure(b_proc, data, uninterruptible_exit, Qnil);
RUBY_VM_CHECK_INTS(cur_th->ec);
return ret;
}
static void
thread_specific_storage_alloc(rb_thread_t *th)
{
VM_ASSERT(th->specific_storage == NULL);
if (UNLIKELY(specific_key_count > 0)) {
th->specific_storage = ZALLOC_N(void *, RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
}
}
rb_internal_thread_specific_key_t
rb_internal_thread_specific_key_create(void)
{
rb_vm_t *vm = GET_VM();
if (specific_key_count == 0 && vm->ractor.cnt > 1) {
rb_raise(rb_eThreadError, "The first rb_internal_thread_specific_key_create() is called with multiple ractors");
}
else if (specific_key_count > RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX) {
rb_raise(rb_eThreadError, "rb_internal_thread_specific_key_create() is called more than %d times", RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
}
else {
rb_internal_thread_specific_key_t key = specific_key_count++;
if (key == 0) {
// allocate
rb_ractor_t *cr = GET_RACTOR();
rb_thread_t *th;
ccan_list_for_each(&cr->threads.set, th, lt_node) {
thread_specific_storage_alloc(th);
}
}
return key;
}
}
// async and native thread safe.
void *
rb_internal_thread_specific_get(VALUE thread_val, rb_internal_thread_specific_key_t key)
{
rb_thread_t *th = DATA_PTR(thread_val);
VM_ASSERT(rb_thread_ptr(thread_val) == th);
VM_ASSERT(key < RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
VM_ASSERT(th->specific_storage);
return th->specific_storage[key];
}
// async and native thread safe.
void
rb_internal_thread_specific_set(VALUE thread_val, rb_internal_thread_specific_key_t key, void *data)
{
rb_thread_t *th = DATA_PTR(thread_val);
VM_ASSERT(rb_thread_ptr(thread_val) == th);
VM_ASSERT(key < RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
VM_ASSERT(th->specific_storage);
th->specific_storage[key] = data;
}
|