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
|
/**
* ██████ ███████ ████████ ██ ██ ██████ ███████ █████ ██████ ██████ ██████ ██████ ██
* ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
* ██████ ███████ ██ ███████ ██████ █████ ███████ ██ ██ ██████ ██ ██ ██ ██ ██
* ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
* ██████ ███████ ██ ██ ██ ██ ██ ███████ ██ ██ ██████ ███████ ██ ██████ ██████ ███████
*
* @file BS_thread_pool_test.cpp
* @author Barak Shoshany (baraksh@gmail.com) (https://baraksh.com/)
* @version 5.1.0
* @date 2026-01-03
* @copyright Copyright (c) 2021-2026 Barak Shoshany. Licensed under the MIT license. If you found this project useful, please consider starring it on GitHub! If you use this library in software of any kind, please provide a link to the GitHub repository https://github.com/bshoshany/thread-pool in the source code and documentation. If you use this library in published research, please cite it as follows: Barak Shoshany, "A C++17 Thread Pool for High-Performance Scientific Computing", doi:10.1016/j.softx.2024.101687, SoftwareX 26 (2024) 101687, arXiv:2105.00613
*
* @brief `BS::thread_pool`: a fast, lightweight, modern, and easy-to-use C++17/C++20/C++23 thread pool library. This program tests all aspects of the library, but is not needed in order to use the library.
*/
// We need to include <version> since if we're using `import std` it will not define any feature-test macros.
#ifdef __has_include
#if __has_include(<version>)
#include <version> // NOLINT(misc-include-cleaner)
#endif
#endif
// If the macro `BS_THREAD_POOL_IMPORT_STD` is defined, import the C++ Standard Library as a module. Otherwise, include the relevant Standard Library header files.
#if defined(BS_THREAD_POOL_IMPORT_STD) && (__cplusplus >= 202004L)
import std;
constexpr bool using_import_std = true;
#else
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <functional>
#include <future>
#include <initializer_list>
#include <iomanip>
#include <ios>
#include <iostream>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <numeric>
#include <optional>
#include <random>
#include <set>
#include <sstream>
#include <string>
#include <string_view>
#include <thread>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
#ifdef __cpp_exceptions
#include <exception>
#include <stdexcept>
#endif
#ifdef __cpp_lib_format
#include <format>
#endif
#ifdef __cpp_lib_semaphore
#include <semaphore>
#endif
constexpr bool using_import_std = false;
#endif
// If the macro `BS_THREAD_POOL_TEST_IMPORT_MODULE` is defined, import the thread pool library as a module. Otherwise, include the header file. We also check that we are in C++20 or later. We can't use `__cpp_modules` to check if modules are supported, because Clang does not define it even in C++20 mode; its support for C++20 modules is only partial, but it does seem to work for this particular library.
#define BS_THREAD_POOL_TEST_VERSION 5, 1, 0
#if defined(BS_THREAD_POOL_TEST_IMPORT_MODULE) && (__cplusplus >= 202002L)
import BS.thread_pool;
static_assert(BS::thread_pool_module, "The flag BS::thread_pool_module is set to false, but the library was imported as a module. Aborting compilation.");
static_assert(BS::thread_pool_version == BS::version(BS_THREAD_POOL_TEST_VERSION), "The versions of BS_thread_pool_test.cpp and the BS.thread_pool module do not match. Aborting compilation.");
#else
#include "BS_thread_pool.hpp"
static_assert(!BS::thread_pool_module, "The flag BS::thread_pool_module is set to true, but the library was not imported as a module. Aborting compilation.");
static_assert(BS::thread_pool_version == BS::version(BS_THREAD_POOL_TEST_VERSION), "The versions of BS_thread_pool_test.cpp and BS_thread_pool.hpp do not match. Aborting compilation.");
#endif
#ifdef BS_THREAD_POOL_NATIVE_EXTENSIONS
static_assert(BS::thread_pool_native_extensions, "Cannot test the native extensions, as the thread pool module was compiled without enabling them using the macro BS_THREAD_POOL_NATIVE_EXTENSIONS. Aborting compilation.");
#endif
namespace {
// A global synced stream which prints to the standard output.
BS::synced_stream sync_cout;
// A global synced stream which prints to a log file.
BS::synced_stream sync_log;
// A flag to enable or disable printing to the standard output.
bool use_stdout = true;
// A flag to enable or disable printing to the log file.
bool use_log = false;
// A flag to enable or disable colored output.
bool no_color = false;
// ================================
// std::counting_semaphore polyfill
// ================================
#ifdef __cpp_lib_semaphore
using std::binary_semaphore;
using std::counting_semaphore;
#else
/**
* @brief A polyfill for `std::counting_semaphore`, to be used if C++20 features are not available. A `counting_semaphore` is a synchronization primitive that allows more than one concurrent access to the same resource. The number of concurrent accessors is limited by the semaphore's counter, which is decremented when a thread acquires the semaphore and incremented when a thread releases the semaphore. If the counter is zero, a thread trying to acquire the semaphore will be blocked until another thread releases the semaphore.
*
* @tparam LeastMaxValue The least maximum value of the counter. (In this implementation, it is also the actual maximum value.)
*/
template <std::ptrdiff_t LeastMaxValue = std::numeric_limits<std::ptrdiff_t>::max()>
class [[nodiscard]] counting_semaphore
{
static_assert(LeastMaxValue >= 0, "The least maximum value for a counting semaphore must not be negative.");
public:
/**
* @brief Construct a new counting semaphore with the given initial counter value.
*
* @param desired The initial counter value.
*/
constexpr explicit counting_semaphore(const std::ptrdiff_t desired) : counter(desired) {}
// The copy and move constructors and assignment operators are deleted. The semaphore cannot be copied or moved.
counting_semaphore(const counting_semaphore&) = delete;
counting_semaphore(counting_semaphore&&) = delete;
counting_semaphore& operator=(const counting_semaphore&) = delete;
counting_semaphore& operator=(counting_semaphore&&) = delete;
~counting_semaphore() = default;
/**
* @brief Returns the internal counter's maximum possible value, which in this implementation is equal to `LeastMaxValue`.
*
* @return The internal counter's maximum possible value.
*/
[[nodiscard]] static constexpr std::ptrdiff_t max() noexcept
{
return LeastMaxValue;
}
/**
* @brief Atomically decrements the internal counter by 1 if it is greater than 0; otherwise blocks until it is greater than 0 and can successfully decrement the internal counter.
*/
void acquire()
{
std::unique_lock lock(mutex);
cv.wait(lock,
[this]
{
return counter > 0;
});
--counter;
}
/**
* @brief Atomically increments the internal counter. Any thread(s) waiting for the counter to be greater than 0, such as due to being blocked in `acquire()`, will subsequently be unblocked.
*
* @param update The amount to increment the internal counter by. Defaults to 1.
*/
void release(const std::ptrdiff_t update = 1)
{
{
const std::scoped_lock lock(mutex);
counter += update;
}
cv.notify_all();
}
/**
* @brief Tries to atomically decrement the internal counter by 1 if it is greater than 0; no blocking occurs regardless.
*
* @return `true` if decremented the internal counter, `false` otherwise.
*/
bool try_acquire()
{
std::scoped_lock lock(mutex);
if (counter > 0)
{
--counter;
return true;
}
return false;
}
/**
* @brief Tries to atomically decrement the internal counter by 1 if it is greater than 0; otherwise blocks until it is greater than 0 and can successfully decrement the internal counter, or the `rel_time` duration has been exceeded.
*
* @tparam Rep An arithmetic type representing the number of ticks to wait.
* @tparam Period An `std::ratio` representing the length of each tick in seconds.
* @param rel_time The duration the function must wait. Note that the function may wait for longer.
* @return `true` if decremented the internal counter, `false` otherwise.
*/
template <class Rep, class Period>
bool try_acquire_for(const std::chrono::duration<Rep, Period>& rel_time)
{
std::unique_lock lock(mutex);
if (!cv.wait_for(lock, rel_time,
[this]
{
return counter > 0;
}))
return false;
--counter;
return true;
}
/**
* @brief Tries to atomically decrement the internal counter by 1 if it is greater than 0; otherwise blocks until it is greater than 0 and can successfully decrement the internal counter, or the `abs_time` time point has been passed.
*
* @tparam Clock The type of the clock used to measure time.
* @tparam Duration An `std::chrono::duration` type used to indicate the time point.
* @param abs_time The earliest time the function must wait until. Note that the function may wait for longer.
* @return `true` if decremented the internal counter, `false` otherwise.
*/
template <class Clock, class Duration>
bool try_acquire_until(const std::chrono::time_point<Clock, Duration>& abs_time)
{
std::unique_lock lock(mutex);
if (!cv.wait_until(lock, abs_time,
[this]
{
return counter > 0;
}))
return false;
--counter;
return true;
}
private:
/**
* @brief A mutex used to synchronize access to the counter.
*/
mutable std::mutex mutex;
/**
* @brief A condition variable used to wait for the counter.
*/
std::condition_variable cv;
/**
* @brief The semaphore's counter.
*/
std::ptrdiff_t counter;
};
/**
* @brief A polyfill for `std::binary_semaphore`, to be used if C++20 features are not available.
*/
using binary_semaphore = counting_semaphore<1>;
#endif
// ======================
// Functions for printing
// ======================
/**
* @brief An enumeration class of ANSI escape codes for formatting terminal output.
*/
enum class ansi : std::uint8_t
{
reset = 0,
bold = 1,
dim = 2,
italic = 3,
underline = 4,
invert = 7,
strike = 9,
double_underline = 21,
normal_intensity = 22,
not_italic = 23,
not_underlined = 24,
fg_black = 30,
fg_red = 31,
fg_green = 32,
fg_yellow = 33,
fg_blue = 34,
fg_magenta = 35,
fg_cyan = 36,
fg_white = 37,
bg_black = 40,
bg_red = 41,
bg_green = 42,
bg_yellow = 43,
bg_blue = 44,
bg_magenta = 45,
bg_cyan = 46,
bg_white = 47,
fg_bright_black = 90,
fg_bright_red = 91,
fg_bright_green = 92,
fg_bright_yellow = 93,
fg_bright_blue = 94,
fg_bright_magenta = 95,
fg_bright_cyan = 96,
fg_bright_white = 97,
bg_bright_black = 100,
bg_bright_red = 101,
bg_bright_green = 102,
bg_bright_yellow = 103,
bg_bright_blue = 104,
bg_bright_magenta = 105,
bg_bright_cyan = 106,
bg_bright_white = 107
};
// Constants for ANSI styles used in this program.
constexpr std::initializer_list<ansi> ansi_error = {ansi::fg_bright_red};
constexpr std::initializer_list<ansi> ansi_info = {ansi::fg_bright_blue};
constexpr std::initializer_list<ansi> ansi_separator = {ansi::fg_bright_yellow};
constexpr std::initializer_list<ansi> ansi_subtitle = {ansi::fg_bright_cyan, ansi::bold};
constexpr std::initializer_list<ansi> ansi_success = {ansi::fg_bright_green};
constexpr std::initializer_list<ansi> ansi_title = {ansi::fg_bright_white, ansi::bold};
constexpr std::initializer_list<ansi> ansi_title_italic = {ansi::fg_bright_white, ansi::bold, ansi::italic};
constexpr std::initializer_list<ansi> ansi_title_underline = {ansi::fg_bright_white, ansi::bold, ansi::underline};
/**
* @brief Output an ANSI escape code to a stream.
*
* @param out The output stream.
* @param code The ANSI code.
* @return The output stream.
*/
inline std::ostream& operator<<(std::ostream& out, const ansi code)
{
if (no_color)
return out;
return out << "\033[" << static_cast<std::uint32_t>(code) << 'm';
}
/**
* @brief Output multiple ANSI escape codes to a stream.
*
* @param out The output stream.
* @param codes The ANSI codes.
* @return The output stream.
*/
inline std::ostream& operator<<(std::ostream& out, const std::initializer_list<ansi> codes)
{
if (no_color)
return out;
out << "\033[";
bool first = true;
for (const ansi code : codes)
{
if (!first)
out << ';';
else
first = false;
out << static_cast<std::uint32_t>(code);
}
return out << 'm';
}
/**
* @brief Print any number of items to the standard output and/or the log file.
*
* @tparam T The types of the items.
* @param items The items to print.
*/
template <typename... T>
void log(const T&... items)
{
if (use_stdout)
sync_cout.print(items...);
if (use_log)
sync_log.print(items...);
}
/**
* @brief Print any number of items to the standard output and/or the log file, followed by a newline character.
*
* @tparam T The types of the items.
* @param items The items to print.
*/
template <typename... T>
void logln(T&&... items)
{
log(std::forward<T>(items)..., '\n');
}
/**
* @brief Print any number of items to the standard output and/or the log file with the specified ANSI styles. The ANSI codes are only printed to the standard output, but both streams receive the printed items.
*
* @tparam T The types of the items.
* @param codes The ANSI codes.
* @param items The items to print.
*/
template <typename... T>
void log_ansi(const std::initializer_list<ansi> codes, const T&... items)
{
if (use_stdout)
sync_cout.print(codes, items..., ansi::reset);
if (use_log)
sync_log.print(items...);
}
/**
* @brief Print any number of items to the standard output and/or the log file with the specified ANSI styles, followed by a newline character. The ANSI codes are only printed to the standard output, but both streams receive the printed items.
*
* @tparam T The types of the items.
* @param codes The ANSI codes.
* @param items The items to print.
*/
template <typename... T>
void logln_ansi(const std::initializer_list<ansi> codes, T&&... items)
{
log_ansi(codes, std::forward<T>(items)..., '\n');
}
/**
* @brief Print a stylized header with the specified ANSI styles.
*
* @param text The text of the header. Will appear between two lines.
* @param symbol The symbol to use for the lines. Default is '='.
* @param codes The ANSI codes. Default is `ansi_separator`.
*/
void print_header(const std::string_view text, const char symbol = '=', const std::initializer_list<ansi> codes = ansi_separator)
{
const std::string separator(text.length(), symbol);
logln_ansi(codes, BS::synced_stream::flush, '\n', separator, '\n', text, '\n', separator);
}
/**
* @brief Print a key followed by values with different ANSI styles.
*
* @tparam T The types of the values.
* @param key The key.
* @param values The values.
*/
template <typename... T>
void print_key_values(const std::string_view key, T&&... values)
{
log_ansi(ansi_title, key);
logln_ansi(ansi_subtitle, std::forward<T>(values)...);
}
// =================================
// Functions for checking conditions
// =================================
/**
* @brief A struct to keep count of the number of tests that succeeded and failed.
*/
struct test_results
{
inline static std::size_t tests_succeeded = 0;
inline static std::size_t tests_failed = 0;
};
/**
* @brief Check if a condition is met, report the result, and keep count of the total number of successes and failures.
*
* @param condition The condition to check.
*/
void check(const bool condition)
{
if (condition)
{
logln_ansi(ansi_success, "-> passed.");
++test_results::tests_succeeded;
}
else
{
logln_ansi(ansi_error, "-> FAILED!");
++test_results::tests_failed;
}
}
/**
* @brief Check if the expected result has been obtained, report the result, and keep count of the total number of successes and failures.
*
* @param expected The expected result.
* @param obtained The obtained result.
*/
template <typename T1, typename T2>
void check(const T1& expected, const T2& obtained)
{
const bool passed = (expected == static_cast<T1>(obtained));
log_ansi(passed ? ansi_success : ansi_error, "- Expected: ", expected, ", obtained: ", obtained, ' ');
check(passed);
}
/**
* @brief Check if all of the flags in a container are equal to the desired value.
*
* @param flags The container.
* @param value The desired value.
* @return `true` if all flags are equal to the desired value, or `false` otherwise.
*/
template <typename T, typename V>
bool all_flags_equal(const T& flags, const V& value)
{
return std::all_of(flags.begin(), flags.end(),
[&value](const auto& flag)
{
return flag == value;
});
}
/**
* @brief Check if all of the flags in a container are set.
*
* @param flags The container.
* @return `true` if all flags are set, or `false` otherwise.
*/
template <typename T>
bool all_flags_set(const T& flags)
{
return std::all_of(flags.begin(), flags.end(),
[](const bool flag)
{
return flag;
});
}
/**
* @brief Check if none of the flags in a container are set.
*
* @param flags The container.
* @return `true` if no flags are set, or `false` otherwise.
*/
template <typename T>
bool no_flags_set(const T& flags)
{
return std::none_of(flags.begin(), flags.end(),
[](const bool flag)
{
return flag;
});
}
// =======================================
// Functions for generating random numbers
// =======================================
/**
* @brief Obtain a random number in a specified range.
*
* @tparam T The type of the values in the range.
* @param min The minimum value of the range.
* @param max The maximum value of the range.
* @return The random number.
*/
template <typename T>
T random(const T min, const T max)
{
static std::random_device rand_device;
static std::mt19937_64 twister(rand_device());
std::uniform_int_distribution<T> dist(min, max);
return dist(twister);
}
/**
* @brief Obtain an ordered pair of two distinct random numbers in a specified range.
*
* @tparam T The type of the values in the range.
* @param min The minimum value of the range.
* @param max The maximum value of the range. Must be larger than `min`.
* @return The random numbers.
*/
template <typename T>
std::pair<T, T> random_pair(const T min, const T max)
{
static std::random_device rand_device;
static std::mt19937_64 twister(rand_device());
std::uniform_int_distribution<T> dist(min, max);
T first = dist(twister);
T second;
do
second = dist(twister);
while (second == first);
if (second < first)
return {second, first};
return {first, second};
}
// ========================================
// Functions for detecting various features
// ========================================
/**
* @brief Make a string out of items of various types.
*
* @tparam T The types of the items.
* @param items The items.
* @return The generated string.
*/
template <typename... T>
std::string make_string(const T&... items)
{
std::ostringstream out;
(out << ... << items);
return out.str();
}
/**
* @brief Detect the compiler used to compile this program.
*
* @return A string describing the compiler.
*/
std::string detect_compiler()
{
#if defined(__apple_build_version__)
return make_string("Apple Clang v", __clang_major__, '.', __clang_minor__, '.', __clang_patchlevel__);
#elif defined(__clang__)
return make_string("Clang v", __clang_major__, '.', __clang_minor__, '.', __clang_patchlevel__);
#elif defined(__GNUC__)
return make_string("GCC v", __GNUC__, '.', __GNUC_MINOR__, '.', __GNUC_PATCHLEVEL__);
#elif defined(_MSC_FULL_VER)
std::string msvc_full_ver = make_string(_MSC_FULL_VER);
return make_string("MSVC v", msvc_full_ver.substr(0, 2), '.', msvc_full_ver.substr(2, 2), '.', msvc_full_ver.substr(4));
#else
return "Other";
#endif
}
/**
* @brief Detect the C++ standard used to compile this program.
*
* @return A string describing the C++ standard.
*/
std::string detect_cpp_standard()
{
#if __cplusplus == 201703L
return "C++17";
#elif __cplusplus == 202002L
return "C++20";
#elif (__cplusplus == 202302L) || (defined(_MSC_VER) && __cplusplus > 202002L) // MSVC with `/std:c++latest` only guarantees `__cplusplus` is "at least one higher" than the highest supported version.
return "C++23";
#else
return "Other";
#endif
}
/**
* @brief Detect the C++ standard library used to compile this program.
*
* @return A string describing the C++ standard library.
*/
std::string detect_lib()
{
#if defined(_LIBCPP_VERSION)
return make_string("LLVM libc++ v", _LIBCPP_VERSION / 10000, '.', (_LIBCPP_VERSION / 100) % 100, '.', _LIBCPP_VERSION % 100); // NOLINT(readability-magic-numbers)
#elif defined(_GLIBCXX_RELEASE)
std::string out = make_string("GNU libstdc++ v", _GLIBCXX_RELEASE);
#ifdef __GLIBCXX__
out += make_string(" (", __GLIBCXX__, ')');
#endif
return out;
#elif defined(_MSVC_STL_VERSION)
std::string out = make_string("Microsoft STL v", _MSVC_STL_VERSION);
#ifdef _MSVC_STL_UPDATE
out += make_string(" (", _MSVC_STL_UPDATE, ')');
#endif
return out;
#else
return "Other";
#endif
}
/**
* @brief Detect the operating system used to compile this program.
*
* @return A string describing the operating system.
*/
std::string detect_os()
{
#if defined(__linux__)
return "Linux";
#elif defined(_WIN32)
return "Windows";
#elif defined(__APPLE__)
return "macOS";
#else
return "Other";
#endif
}
/**
* @brief Detect available C++ features and print them out.
*/
void print_features()
{
constexpr int width = 35;
log(std::left);
log_ansi(ansi_title, std::setw(width), "* __cpp_concepts:");
#ifdef __cpp_concepts
logln_ansi(ansi_subtitle, __cpp_concepts);
#else
logln_ansi(ansi_subtitle, "N/A");
#endif
log_ansi(ansi_title, std::setw(width), "* __cpp_exceptions:");
#ifdef __cpp_exceptions
logln_ansi(ansi_subtitle, __cpp_exceptions);
#else
logln_ansi(ansi_subtitle, "N/A");
#endif
log_ansi(ansi_title, std::setw(width), "* __cpp_impl_three_way_comparison:");
#ifdef __cpp_impl_three_way_comparison
logln_ansi(ansi_subtitle, __cpp_impl_three_way_comparison);
#else
logln_ansi(ansi_subtitle, "N/A");
#endif
log_ansi(ansi_title, std::setw(width), "* __cpp_lib_format:");
#ifdef __cpp_lib_format
logln_ansi(ansi_subtitle, __cpp_lib_format);
#else
logln_ansi(ansi_subtitle, "N/A");
#endif
log_ansi(ansi_title, std::setw(width), "* __cpp_lib_int_pow2:");
#ifdef __cpp_lib_int_pow2
logln_ansi(ansi_subtitle, __cpp_lib_int_pow2);
#else
logln_ansi(ansi_subtitle, "N/A");
#endif
log_ansi(ansi_title, std::setw(width), "* __cpp_lib_jthread:");
#ifdef __cpp_lib_jthread
logln_ansi(ansi_subtitle, __cpp_lib_jthread);
#else
logln_ansi(ansi_subtitle, "N/A");
#endif
log_ansi(ansi_title, std::setw(width), "* __cpp_lib_modules:");
#ifdef __cpp_lib_modules
logln_ansi(ansi_subtitle, __cpp_lib_modules);
#else
logln_ansi(ansi_subtitle, "N/A");
#endif
log_ansi(ansi_title, std::setw(width), "* __cpp_lib_move_only_function:");
#ifdef __cpp_lib_move_only_function
logln_ansi(ansi_subtitle, __cpp_lib_move_only_function);
#else
logln_ansi(ansi_subtitle, "N/A");
#endif
log_ansi(ansi_title, std::setw(width), "* __cpp_lib_semaphore:");
#ifdef __cpp_lib_semaphore
logln_ansi(ansi_subtitle, __cpp_lib_semaphore);
#else
logln_ansi(ansi_subtitle, "N/A");
#endif
log_ansi(ansi_title, std::setw(width), "* __cpp_modules:");
#ifdef __cpp_modules
logln_ansi(ansi_subtitle, __cpp_modules);
#else
logln_ansi(ansi_subtitle, "N/A");
#endif
log_ansi(ansi_title, std::setw(width), "* __has_include(<version>):");
#if __has_include(<version>)
logln_ansi(ansi_subtitle, "true");
#else
logln_ansi(ansi_subtitle, "false");
#endif
logln(std::right);
}
// =========================================
// Functions to verify the number of threads
// =========================================
/**
* @brief Obtain a list of unique thread IDs in the pool. Submits a number of tasks equal to twice the thread count into the pool. Each task stores the ID of the thread running it, and then waits until as many tasks as the thread count are finished. This ensures that each thread in the pool runs at least one task, as the pool gets filled completely.
*
* @param pool The thread pool to check.
*/
std::vector<std::thread::id> obtain_unique_threads(BS::thread_pool<>& pool)
{
const std::size_t num_tasks = pool.get_thread_count() * 2;
std::vector<std::thread::id> thread_ids(num_tasks);
std::atomic<std::size_t> total_count = 0;
counting_semaphore sem(0);
for (std::thread::id& tid : thread_ids)
{
pool.detach_task(
[&total_count, &tid, &sem, thread_count = pool.get_thread_count(), num_tasks]
{
tid = std::this_thread::get_id();
if (++total_count == thread_count)
sem.release(static_cast<std::ptrdiff_t>(num_tasks));
sem.acquire();
});
}
pool.wait();
std::sort(thread_ids.begin(), thread_ids.end());
const std::vector<std::thread::id>::iterator last = std::unique(thread_ids.begin(), thread_ids.end());
thread_ids.erase(last, thread_ids.end());
return thread_ids;
}
/**
* @brief Check that the constructor works. Also checks that get_thread_ids() reports the correct IDs.
*/
void check_constructor()
{
BS::thread_pool pool;
logln("Checking that the thread pool reports a number of threads equal to the hardware concurrency...");
check(std::thread::hardware_concurrency(), pool.get_thread_count());
logln("Checking that the manually counted number of unique thread IDs is equal to the reported number of threads...");
const std::vector<std::thread::id> unique_threads = obtain_unique_threads(pool);
check(pool.get_thread_count(), unique_threads.size());
logln("Checking that the unique thread IDs obtained are the same as those reported by get_thread_ids()...");
std::vector<std::thread::id> threads_from_pool = pool.get_thread_ids();
std::sort(threads_from_pool.begin(), threads_from_pool.end());
check(threads_from_pool == unique_threads);
}
/**
* @brief Check that reset() works.
*/
void check_reset()
{
BS::thread_pool pool;
pool.reset(static_cast<std::size_t>(std::thread::hardware_concurrency()) * 2);
logln("Checking that after reset() the thread pool reports a number of threads equal to double the hardware concurrency...");
check(std::thread::hardware_concurrency() * 2, pool.get_thread_count());
logln("Checking that after reset() the manually counted number of unique thread IDs is equal to the reported number of threads...");
check(pool.get_thread_count(), obtain_unique_threads(pool).size());
pool.reset(std::thread::hardware_concurrency());
logln("Checking that after a second reset() the thread pool reports a number of threads equal to the hardware concurrency...");
check(std::thread::hardware_concurrency(), pool.get_thread_count());
logln("Checking that after a second reset() the manually counted number of unique thread IDs is equal to the reported number of threads...");
check(pool.get_thread_count(), obtain_unique_threads(pool).size());
}
// =======================================
// Functions to verify submission of tasks
// =======================================
/**
* @brief A class used to detect when a copy or move constructor has been invoked.
*/
class [[nodiscard]] detect_copy_move
{
public:
detect_copy_move() = default;
detect_copy_move(const detect_copy_move& /*other*/) : copied(true) {}
detect_copy_move(detect_copy_move&& /*other*/) noexcept : moved(true) {}
detect_copy_move& operator=(const detect_copy_move&) = delete;
detect_copy_move& operator=(detect_copy_move&&) = delete;
~detect_copy_move() = default;
[[nodiscard]] bool get_copied() const
{
return copied;
};
[[nodiscard]] bool get_moved() const
{
return moved;
};
private:
bool copied = false;
bool moved = false;
}; // class detect_copy_move
/**
* @brief Check that detach_task() or submit_task() work.
*
* @param which_func A string naming the function to check.
*/
void check_task(const std::string_view which_func)
{
BS::thread_pool pool;
logln("Checking that ", which_func, " works for a function with no arguments or return value...");
{
bool flag = false;
const auto func = [&flag]
{
flag = true;
};
if (which_func == "detach_task()")
{
pool.detach_task(func);
pool.wait();
}
else
{
pool.submit_task(func).wait();
}
check(flag);
}
logln("Checking that ", which_func, " works for a function with one argument and no return value...");
{
bool flag = false;
const auto func = [](bool& flag_)
{
flag_ = true;
};
if (which_func == "detach_task()")
{
pool.detach_task(
[&func, &flag]
{
func(flag);
});
pool.wait();
}
else
{
pool.submit_task(
[&func, &flag]
{
func(flag);
})
.wait();
}
check(flag);
}
logln("Checking that ", which_func, " works for a function with two arguments and no return value...");
{
bool flag1 = false;
bool flag2 = false;
const auto func = [](bool& flag1_, bool& flag2_)
{
flag1_ = flag2_ = true;
};
if (which_func == "detach_task()")
{
pool.detach_task(
[&func, &flag1, &flag2]
{
func(flag1, flag2);
});
pool.wait();
}
else
{
pool.submit_task(
[&func, &flag1, &flag2]
{
func(flag1, flag2);
})
.wait();
}
check(flag1 && flag2);
}
if (which_func == "submit_task()")
{
logln("Checking that submit_task() works for a function with no arguments and a return value...");
{
bool flag = false;
const auto func = [&flag]
{
return (flag = true);
};
std::future<bool> flag_future = pool.submit_task(func);
check(flag_future.get() && flag);
}
logln("Checking that submit_task() works for a function with one argument and a return value...");
{
bool flag = false;
const auto func = [](bool& flag_)
{
return (flag_ = true);
};
std::future<bool> flag_future = pool.submit_task(
[&func, &flag]
{
return func(flag);
});
check(flag_future.get() && flag);
}
logln("Checking that submit_task() works for a function with two arguments and a return value...");
{
bool flag1 = false;
bool flag2 = false;
const auto func = [](bool& flag1_, bool& flag2_)
{
return (flag1_ = flag2_ = true);
};
std::future<bool> flag_future = pool.submit_task(
[&func, &flag1, &flag2]
{
return func(flag1, flag2);
});
check(flag_future.get() && flag1 && flag2);
}
}
logln("Checking that ", which_func, " does not create unnecessary copies of the function object...");
{
bool copied = false;
bool moved = false;
auto test_copy = [detect = detect_copy_move(), &copied, &moved]
{
copied = detect.get_copied();
moved = detect.get_moved();
};
if (which_func == "detach_task()")
{
pool.detach_task(std::move(test_copy));
pool.wait();
}
else
{
pool.submit_task(std::move(test_copy)).wait();
}
check(!copied && moved);
}
logln("Checking that ", which_func, " correctly accepts arguments passed by value, reference, and constant reference...");
{
{
logln("Value:");
const std::int64_t pass_me_by_value = 0;
const auto func_value = [](std::int64_t passed_by_value)
{
if (++passed_by_value != 1)
static_cast<void>(0);
};
if (which_func == "detach_task()")
{
pool.detach_task(
[&func_value, pbv = pass_me_by_value]
{
func_value(pbv);
});
pool.wait();
}
else
{
pool.submit_task(
[&func_value, pbv = pass_me_by_value]
{
func_value(pbv);
})
.wait();
}
check(pass_me_by_value == 0);
}
{
logln("Reference:");
std::int64_t pass_me_by_ref = 0;
const auto func_ref = [](std::int64_t& passed_by_ref)
{
++passed_by_ref;
};
if (which_func == "detach_task()")
{
pool.detach_task(
[&func_ref, &pass_me_by_ref]
{
func_ref(pass_me_by_ref);
});
pool.wait();
}
else
{
pool.submit_task(
[&func_ref, &pass_me_by_ref]
{
func_ref(pass_me_by_ref);
})
.wait();
}
check(pass_me_by_ref == 1);
}
{
logln("Constant reference:");
std::int64_t pass_me_by_cref = 0;
binary_semaphore sem(0);
const auto func_cref = [&sem](const std::int64_t& passed_by_cref)
{
sem.acquire();
check(passed_by_cref == 1);
};
if (which_func == "detach_task()")
{
pool.detach_task(
[&func_cref, &pass_me_by_cref = std::as_const(pass_me_by_cref)]
{
func_cref(pass_me_by_cref);
});
++pass_me_by_cref;
sem.release();
pool.wait();
}
else
{
const std::future<void> future = pool.submit_task(
[&func_cref, &pass_me_by_cref = std::as_const(pass_me_by_cref)]
{
func_cref(pass_me_by_cref);
});
++pass_me_by_cref;
sem.release();
future.wait();
}
}
}
}
/**
* @brief A class to facilitate checking that member functions of different types have been successfully submitted.
*/
class [[nodiscard]] flag_class
{
public:
explicit flag_class(BS::thread_pool<>& pool_) : pool(&pool_) {}
void set_flag_no_args()
{
flag = true;
}
void set_flag_one_arg(const bool arg)
{
flag = arg;
}
[[nodiscard]] bool set_flag_no_args_return()
{
return (flag = true);
}
[[nodiscard]] bool set_flag_one_arg_return(const bool arg)
{
return (flag = arg);
}
[[nodiscard]] bool get_flag() const
{
return flag;
}
void detach_test_flag_no_args()
{
pool->detach_task(
[this]
{
set_flag_no_args();
});
pool->wait();
check(get_flag());
}
void detach_test_flag_one_arg()
{
pool->detach_task(
[this]
{
set_flag_one_arg(true);
});
pool->wait();
check(get_flag());
}
void submit_test_flag_no_args()
{
pool->submit_task(
[this]
{
set_flag_no_args();
})
.wait();
check(get_flag());
}
void submit_test_flag_one_arg()
{
pool->submit_task(
[this]
{
set_flag_one_arg(true);
})
.wait();
check(get_flag());
}
void submit_test_flag_no_args_return()
{
std::future<bool> flag_future = pool->submit_task(
[this]
{
return set_flag_no_args_return();
});
check(flag_future.get() && get_flag());
}
void submit_test_flag_one_arg_return()
{
std::future<bool> flag_future = pool->submit_task(
[this]
{
return set_flag_one_arg_return(true);
});
check(flag_future.get() && get_flag());
}
private:
bool flag = false;
BS::thread_pool<>* pool;
}; // class flag_class
/**
* @brief Check that submitting member functions works.
*/
void check_member_function()
{
BS::thread_pool pool;
logln("Checking that detach_task() works for a member function with no arguments or return value...");
{
flag_class flag(pool);
pool.detach_task(
[&flag]
{
flag.set_flag_no_args();
});
pool.wait();
check(flag.get_flag());
}
logln("Checking that detach_task() works for a member function with one argument and no return value...");
{
flag_class flag(pool);
pool.detach_task(
[&flag]
{
flag.set_flag_one_arg(true);
});
pool.wait();
check(flag.get_flag());
}
logln("Checking that submit_task() works for a member function with no arguments or return value...");
{
flag_class flag(pool);
pool.submit_task(
[&flag]
{
flag.set_flag_no_args();
})
.wait();
check(flag.get_flag());
}
logln("Checking that submit_task() works for a member function with one argument and no return value...");
{
flag_class flag(pool);
pool.submit_task(
[&flag]
{
flag.set_flag_one_arg(true);
})
.wait();
check(flag.get_flag());
}
logln("Checking that submit_task() works for a member function with no arguments and a return value...");
{
flag_class flag(pool);
std::future<bool> flag_future = pool.submit_task(
[&flag]
{
return flag.set_flag_no_args_return();
});
check(flag_future.get() && flag.get_flag());
}
logln("Checking that submit_task() works for a member function with one argument and a return value...");
{
flag_class flag(pool);
std::future<bool> flag_future = pool.submit_task(
[&flag]
{
return flag.set_flag_one_arg_return(true);
});
check(flag_future.get() && flag.get_flag());
}
}
/**
* @brief Check that submitting member functions within an object works.
*/
void check_member_function_within_object()
{
BS::thread_pool pool;
logln("Checking that detach_task() works within an object for a member function with no arguments or return value...");
{
flag_class flag(pool);
flag.detach_test_flag_no_args();
}
logln("Checking that detach_task() works within an object for a member function with one argument and no return value...");
{
flag_class flag(pool);
flag.detach_test_flag_one_arg();
}
logln("Checking that submit_task() works within an object for a member function with no arguments or return value...");
{
flag_class flag(pool);
flag.submit_test_flag_no_args();
}
logln("Checking that submit_task() works within an object for a member function with one argument and no return value...");
{
flag_class flag(pool);
flag.submit_test_flag_one_arg();
}
logln("Checking that submit_task() works within an object for a member function with no arguments and a return value...");
{
flag_class flag(pool);
flag.submit_test_flag_no_args_return();
}
logln("Checking that submit_task() works within an object for a member function with one argument and a return value...");
{
flag_class flag(pool);
flag.submit_test_flag_one_arg_return();
}
}
std::atomic<bool> check_callables_flag = false;
void normal_func()
{
check_callables_flag = true;
}
struct function_object
{
void operator()()
{
check_callables_flag = true;
}
};
struct has_member_function
{
static void member_function()
{
check_callables_flag = true;
}
};
/**
* @brief Check that different callable types are accepted by the thread pool.
*/
void check_callables()
{
BS::thread_pool pool;
logln("Checking normal function...");
pool.submit_task(normal_func).wait();
check(check_callables_flag);
logln("Checking function pointer...");
check_callables_flag = false;
void (*const func_ptr)() = normal_func; // NOLINT(misc-const-correctness)
pool.submit_task(func_ptr).wait();
check(check_callables_flag);
logln("Checking pointer to static member function...");
check_callables_flag = false;
auto member_func_ptr = has_member_function::member_function;
pool.submit_task(member_func_ptr).wait();
check(check_callables_flag);
logln("Checking lambda expression...");
check_callables_flag = false;
const auto lambda = []
{
check_callables_flag = true;
};
pool.submit_task(lambda).wait();
check(check_callables_flag);
logln("Checking std::function...");
check_callables_flag = false;
const std::function<void()> function = []
{
check_callables_flag = true;
};
pool.submit_task(function).wait();
check(check_callables_flag);
#ifdef __cpp_lib_move_only_function
logln("Checking std::move_only_function...");
check_callables_flag = false;
std::move_only_function<void()> move_only_function = []
{
check_callables_flag = true;
};
pool.submit_task(std::move(move_only_function)).wait();
check(check_callables_flag);
#else
logln_ansi(ansi_info, "Note: std::move_only_function not available, skipping the corresponding test.");
#endif
logln("Checking std::bind...");
check_callables_flag = false;
const auto lambda_for_bind = [](std::atomic<bool>& flag)
{
flag = true;
};
pool.submit_task(std::bind(lambda_for_bind, std::ref(check_callables_flag))).wait();
check(check_callables_flag);
logln("Checking function object...");
check_callables_flag = false;
const function_object func_obj_instance;
pool.submit_task(func_obj_instance).wait();
check(check_callables_flag);
}
// =====================================
// Functions to verify waiting for tasks
// =====================================
/**
* @brief Check that wait() works.
*/
void check_wait()
{
constexpr std::chrono::milliseconds sleep_time(10);
BS::thread_pool pool;
const std::size_t num_tasks = pool.get_thread_count() * 10;
std::vector<std::atomic<bool>> flags(num_tasks);
for (std::size_t i = 0; i < num_tasks; ++i)
{
pool.detach_task(
[&flags, i, sleep_time]
{
std::this_thread::sleep_for(sleep_time);
flags[i] = true;
});
}
logln("Waiting for tasks...");
pool.wait();
check(all_flags_set(flags));
}
/**
* @brief Check that wait() correctly blocks all external threads that call it.
*/
void check_wait_blocks()
{
constexpr std::chrono::milliseconds sleep_time(100);
constexpr std::size_t num_waiting_tasks = 4;
BS::thread_pool pool;
binary_semaphore sem(0);
logln("Checking that wait() correctly blocks all external threads that call it...");
pool.detach_task(
[&sem]
{
logln("Task submitted to pool 1 and waiting to be released...");
sem.acquire();
logln("Task released.");
});
BS::thread_pool temp_pool(num_waiting_tasks);
std::vector<std::atomic<bool>> flags(num_waiting_tasks);
const auto waiting_task = [&flags, &pool](const std::size_t task_num)
{
logln("Task ", task_num, " submitted to pool 2 and waiting for pool 1's task to finish...");
pool.wait();
logln("Task ", task_num, " finished waiting.");
flags[task_num] = true;
};
for (std::size_t i = 0; i < num_waiting_tasks; ++i)
{
temp_pool.detach_task(
[&waiting_task, i]
{
waiting_task(i);
});
}
std::this_thread::sleep_for(sleep_time);
check(no_flags_set(flags));
sem.release();
temp_pool.wait();
check(all_flags_set(flags));
}
/**
* @brief Check that wait_for() works.
*/
void check_wait_for()
{
constexpr std::chrono::milliseconds long_sleep_time(250);
constexpr std::chrono::milliseconds short_sleep_time(10);
BS::thread_pool pool;
logln("Checking that wait_for() works...");
std::atomic<bool> done = false;
pool.detach_task(
[&done, long_sleep_time]
{
std::this_thread::sleep_for(long_sleep_time);
done = true;
});
logln("Task that lasts ", long_sleep_time.count(), "ms submitted. Waiting for ", short_sleep_time.count(), "ms...");
pool.wait_for(short_sleep_time);
check(!done);
logln("Waiting for ", long_sleep_time.count() * 2, "ms...");
pool.wait_for(long_sleep_time * 2);
check(done);
}
/**
* @brief Check that wait_until() works.
*/
void check_wait_until()
{
constexpr std::chrono::milliseconds long_sleep_time(250);
constexpr std::chrono::milliseconds short_sleep_time(10);
BS::thread_pool pool;
logln("Checking that wait_until() works...");
std::atomic<bool> done = false;
pool.detach_task(
[&done, long_sleep_time]
{
std::this_thread::sleep_for(long_sleep_time);
done = true;
});
const std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
logln("Task that lasts ", long_sleep_time.count(), "ms submitted. Waiting until ", short_sleep_time.count(), "ms from submission time...");
pool.wait_until(now + short_sleep_time);
check(!done);
logln("Waiting until ", long_sleep_time.count() * 2, "ms from submission time...");
pool.wait_until(now + long_sleep_time * 2);
check(done);
}
// An auxiliary thread pool used by check_wait_multiple_deadlock(). It's a global variable so that the program will not get stuck upon destruction of this pool if a deadlock actually occurs.
BS::thread_pool check_wait_multiple_deadlock_pool;
/**
* @brief Check that calling wait() more than once doesn't create a deadlock.
*/
void check_wait_multiple_deadlock()
{
constexpr std::chrono::milliseconds sleep_time(500);
constexpr std::size_t n_waiting_tasks = 1000;
logln("Checking for deadlocks when waiting for tasks...");
BS::thread_pool pool(1);
pool.detach_task(
[sleep_time]
{
std::this_thread::sleep_for(sleep_time);
});
std::atomic<std::size_t> count = 0;
for (std::size_t j = 0; j < n_waiting_tasks; ++j)
{
check_wait_multiple_deadlock_pool.detach_task(
[&pool, &count]
{
pool.wait();
++count;
});
}
bool passed = false;
while (true)
{
const std::size_t old_count = count;
check_wait_multiple_deadlock_pool.wait_for(sleep_time * 2);
if (count == n_waiting_tasks)
{
logln_ansi(ansi_success, "All waiting tasks successfully finished!");
passed = true;
break;
}
if (count == old_count)
{
logln_ansi(ansi_error, "Error: deadlock detected!");
passed = false;
break;
}
logln(count, " tasks out of ", n_waiting_tasks, " finished waiting...");
}
check(passed);
}
#ifdef __cpp_exceptions
// An auxiliary thread pool used by check_wait_self_deadlock(). It's a global variable so that the program will not get stuck upon destruction of this pool if a deadlock actually occurs.
BS::wdc_thread_pool check_wait_self_deadlock_pool;
/**
* @brief Check that calling wait() from within a thread of the same pool throws an exception instead of creating a deadlock.
*/
void check_wait_self_deadlock()
{
constexpr std::chrono::milliseconds sleep_time(100);
logln("Checking for deadlocks when waiting from within a thread of the same pool...");
std::atomic<bool> passed = false;
check_wait_self_deadlock_pool.detach_task(
[&passed]
{
try
{
check_wait_self_deadlock_pool.wait();
}
catch (const BS::wait_deadlock&)
{
passed = true;
}
});
check_wait_self_deadlock_pool.wait_for(sleep_time);
check(passed);
}
#endif
// ========================================
// Functions to verify loop parallelization
// ========================================
/**
* @brief Check that detach_loop() or submit_loop() work for a specific range of indices split over a specific number of tasks, with no return value.
*
* @param pool The thread pool to check.
* @param random_start The first index in the loop.
* @param random_end The last index in the loop plus 1.
* @param num_tasks The number of tasks.
* @param which_func A string naming the function to check.
* @return `true` if the check succeeded, `false` otherwise.
*/
bool check_loop_no_return(BS::thread_pool<>& pool, const std::int64_t random_start, const std::int64_t random_end, const std::size_t num_tasks, const std::string_view which_func)
{
logln("Verifying that ", which_func, " from ", random_start, " to ", random_end, " with ", num_tasks, num_tasks == 1 ? " task" : " tasks", " modifies all indices exactly once...");
const std::size_t num_indices = static_cast<std::size_t>(random_end - random_start);
std::vector<std::atomic<std::int64_t>> flags(num_indices);
std::atomic<bool> indices_out_of_range = false;
const auto loop = [&flags, random_start, random_end, &indices_out_of_range](const std::int64_t idx)
{
if (idx < random_start || idx >= random_end)
indices_out_of_range = true;
else
++flags[static_cast<std::size_t>(idx - random_start)];
};
if (which_func == "detach_loop()")
{
pool.detach_loop(random_start, random_end, loop, num_tasks);
pool.wait();
}
else
{
pool.submit_loop(random_start, random_end, loop, num_tasks).wait();
}
if (indices_out_of_range)
{
logln_ansi(ansi_error, "Error: Loop indices out of range!");
return false;
}
return all_flags_equal(flags, 1);
}
/**
* @brief Check that detach_loop() and submit_loop() work using several different random values for the range of indices and number of tasks.
*/
void check_loop()
{
constexpr std::int64_t range = 1000000;
constexpr std::size_t repeats = 10;
BS::thread_pool pool;
for (std::size_t i = 0; i < repeats; ++i)
{
const std::pair<std::int64_t, std::int64_t> indices = random_pair(-range, range);
check(check_loop_no_return(pool, indices.first, indices.second, random<std::size_t>(1, pool.get_thread_count()), "detach_loop()"));
}
for (std::size_t i = 0; i < repeats; ++i)
{
const std::pair<std::int64_t, std::int64_t> indices = random_pair(-range, range);
check(check_loop_no_return(pool, indices.first, indices.second, random<std::size_t>(1, pool.get_thread_count()), "submit_loop()"));
}
logln("Verifying that detach_loop() with identical start and end indices does nothing...");
{
std::atomic<std::size_t> count = 0;
const std::int64_t index = random(-range, range);
logln("Range: ", index, " to ", index);
pool.detach_loop(index, index,
[&count](const std::int64_t)
{
++count;
});
pool.wait();
check(count == 0);
}
logln("Verifying that submit_loop() with identical start and end indices does nothing...");
{
std::atomic<std::size_t> count = 0;
const std::int64_t index = random(-range, range);
logln("Range: ", index, " to ", index);
pool.submit_loop(index, index,
[&count](const std::int64_t)
{
++count;
})
.wait();
check(count == 0);
}
logln("Verifying that detach_loop() with end index smaller than the start index does nothing...");
{
std::atomic<std::size_t> count = 0;
const std::pair<std::int64_t, std::int64_t> indices = random_pair(-range, range);
logln("Range: ", indices.second, " to ", indices.first);
pool.detach_loop(indices.second, indices.first,
[&count](const std::int64_t)
{
++count;
});
pool.wait();
check(count == 0);
}
logln("Verifying that submit_loop() with end index smaller than the start index does nothing...");
{
std::atomic<std::size_t> count = 0;
const std::pair<std::int64_t, std::int64_t> indices = random_pair(-range, range);
logln("Range: ", indices.second, " to ", indices.first);
pool.submit_loop(indices.second, indices.first,
[&count](const std::int64_t)
{
++count;
})
.wait();
check(count == 0);
}
logln("Trying detach_loop() with a number of tasks larger than the number of indices:");
{
const std::int64_t start = random(-range, range);
check(check_loop_no_return(pool, start, start + random<std::int64_t>(0, static_cast<std::int64_t>(pool.get_thread_count() * 2)), random<std::size_t>(pool.get_thread_count() * 2, pool.get_thread_count() * 4), "detach_loop()"));
}
logln("Trying submit_loop() with a number of tasks larger than the number of indices:");
{
const std::int64_t start = random(-range, range);
check(check_loop_no_return(pool, start, start + random<std::int64_t>(0, static_cast<std::int64_t>(pool.get_thread_count() * 2)), random<std::size_t>(pool.get_thread_count() * 2, pool.get_thread_count() * 4), "submit_loop()"));
}
}
/**
* @brief Check that detach_blocks() or submit_blocks() work for a specific range of indices split over a specific number of tasks, with no return value.
*
* @param pool The thread pool to check.
* @param random_start The first index in the loop.
* @param random_end The last index in the loop plus 1.
* @param num_tasks The number of tasks.
* @param which_func A string naming the function to check.
* @return `true` if the check succeeded, `false` otherwise.
*/
bool check_blocks_no_return(BS::thread_pool<>& pool, const std::int64_t random_start, const std::int64_t random_end, const std::size_t num_tasks, const std::string_view which_func)
{
logln("Verifying that ", which_func, " from ", random_start, " to ", random_end, " with ", num_tasks, num_tasks == 1 ? " task" : " tasks", " modifies all indices exactly once...");
const std::size_t num_indices = static_cast<std::size_t>(random_end - random_start);
std::vector<std::atomic<std::int64_t>> flags(num_indices);
std::atomic<bool> indices_out_of_range = false;
const auto loop = [&flags, random_start, random_end, &indices_out_of_range](const std::int64_t start, const std::int64_t end)
{
if (start < random_start || end > random_end)
{
indices_out_of_range = true;
}
else
{
for (std::int64_t i = start; i < end; ++i)
++flags[static_cast<std::size_t>(i - random_start)];
}
};
if (which_func == "detach_blocks()")
{
pool.detach_blocks(random_start, random_end, loop, num_tasks);
pool.wait();
}
else
{
pool.submit_blocks(random_start, random_end, loop, num_tasks).wait();
}
if (indices_out_of_range)
{
logln_ansi(ansi_error, "Error: Block indices out of range!");
return false;
}
return all_flags_equal(flags, 1);
}
/**
* @brief Check that submit_blocks() works for a specific range of indices split over a specific number of tasks, with a return value.
*
* @param pool The thread pool to check.
* @param random_start The first index in the loop.
* @param random_end The last index in the loop plus 1.
* @param num_tasks The number of tasks.
*/
void check_blocks_return(BS::thread_pool<>& pool, const std::int64_t random_start, const std::int64_t random_end, const std::size_t num_tasks)
{
logln("Verifying that submit_blocks() from ", random_start, " to ", random_end, " with ", num_tasks, num_tasks == 1 ? " task" : " tasks", " correctly sums all indices...");
const auto loop = [](const std::int64_t start, const std::int64_t end)
{
std::int64_t total = 0;
for (std::int64_t i = start; i < end; ++i)
total += i;
return total;
};
const std::vector<std::int64_t> sums_vector = pool.submit_blocks(random_start, random_end, loop, num_tasks).get();
std::int64_t sum = 0;
for (const std::int64_t partial_sum : sums_vector)
sum += partial_sum;
check(std::abs(random_start - random_end) * (random_start + random_end - 1) / 2, sum);
}
/**
* @brief Check that detach_blocks() and submit_blocks() work using several different random values for the range of indices and number of tasks.
*/
void check_blocks()
{
constexpr std::int64_t range = 1000000;
constexpr std::size_t repeats = 10;
BS::thread_pool pool;
for (std::size_t i = 0; i < repeats; ++i)
{
const std::pair<std::int64_t, std::int64_t> indices = random_pair(-range, range);
check(check_blocks_no_return(pool, indices.first, indices.second, random<std::size_t>(1, pool.get_thread_count()), "detach_blocks()"));
}
for (std::size_t i = 0; i < repeats; ++i)
{
const std::pair<std::int64_t, std::int64_t> indices = random_pair(-range, range);
check(check_blocks_no_return(pool, indices.first, indices.second, random<std::size_t>(1, pool.get_thread_count()), "submit_blocks()"));
}
for (std::size_t i = 0; i < repeats; ++i)
{
const std::pair<std::int64_t, std::int64_t> indices = random_pair(-range, range);
check_blocks_return(pool, indices.first, indices.second, random<std::size_t>(1, pool.get_thread_count()));
}
logln("Verifying that detach_blocks() with identical start and end indices does nothing...");
{
std::atomic<std::size_t> count = 0;
const std::int64_t index = random(-range, range);
logln("Range: ", index, " to ", index);
pool.detach_blocks(index, index,
[&count](const std::int64_t, const std::int64_t)
{
++count;
});
pool.wait();
check(count == 0);
}
logln("Verifying that submit_blocks() with identical start and end indices does nothing...");
{
std::atomic<std::size_t> count = 0;
const std::int64_t index = random(-range, range);
logln("Range: ", index, " to ", index);
pool.submit_blocks(index, index,
[&count](const std::int64_t, const std::int64_t)
{
++count;
})
.wait();
check(count == 0);
}
logln("Verifying that detach_blocks() with end index smaller than the start index does nothing...");
{
std::atomic<std::size_t> count = 0;
const std::pair<std::int64_t, std::int64_t> indices = random_pair(-range, range);
logln("Range: ", indices.second, " to ", indices.first);
pool.detach_blocks(indices.second, indices.first,
[&count](const std::int64_t, const std::int64_t)
{
++count;
});
pool.wait();
check(count == 0);
}
logln("Verifying that submit_blocks() with end index smaller than the start index does nothing...");
{
std::atomic<std::size_t> count = 0;
const std::pair<std::int64_t, std::int64_t> indices = random_pair(-range, range);
logln("Range: ", indices.second, " to ", indices.first);
pool.submit_blocks(indices.second, indices.first,
[&count](const std::int64_t, const std::int64_t)
{
++count;
})
.wait();
check(count == 0);
}
logln("Trying detach_blocks() with a number of tasks larger than the number of indices:");
{
const std::int64_t start = random(-range, range);
check(check_blocks_no_return(pool, start, start + random<std::int64_t>(0, static_cast<std::int64_t>(pool.get_thread_count() * 2)), random<std::size_t>(pool.get_thread_count() * 2, pool.get_thread_count() * 4), "detach_blocks()"));
}
logln("Trying submit_blocks() with a number of tasks larger than the number of indices:");
{
const std::int64_t start = random(-range, range);
check(check_blocks_no_return(pool, start, start + random<std::int64_t>(0, static_cast<std::int64_t>(pool.get_thread_count() * 2)), random<std::size_t>(pool.get_thread_count() * 2, pool.get_thread_count() * 4), "submit_blocks()"));
}
}
// ============================================
// Functions to verify sequence parallelization
// ============================================
/**
* @brief Check that detach_sequence() or submit_sequence() work for a specific range of indices, with no return value.
*
* @param pool The thread pool to check.
* @param random_start The first index in the sequence.
* @param random_end The last index in the sequence plus 1.
* @param which_func A string naming the function to check.
* @return `true` if the check succeeded, `false` otherwise.
*/
bool check_sequence_no_return(BS::thread_pool<>& pool, const std::int64_t random_start, const std::int64_t random_end, const std::string_view which_func)
{
logln("Verifying that ", which_func, " from ", random_start, " to ", random_end, " modifies all indices exactly once...");
const std::size_t num_indices = static_cast<std::size_t>(random_end - random_start);
std::vector<std::atomic<std::int64_t>> flags(num_indices);
std::atomic<bool> indices_out_of_range = false;
const auto sequence = [&flags, random_start, random_end, &indices_out_of_range](const std::int64_t index)
{
if (index < random_start || index >= random_end)
indices_out_of_range = true;
else
++flags[static_cast<std::size_t>(index - random_start)];
};
if (which_func == "detach_sequence()")
{
pool.detach_sequence(random_start, random_end, sequence);
pool.wait();
}
else
{
pool.submit_sequence(random_start, random_end, sequence).wait();
}
if (indices_out_of_range)
{
logln_ansi(ansi_error, "Error: Sequence indices out of range!");
return false;
}
return all_flags_equal(flags, 1);
}
/**
* @brief Check that submit_sequence() works for a specific range of indices, with a return value.
*
* @param pool The thread pool to check.
* @param random_start The first index in the sequence.
* @param random_end The last index in the sequence plus 1.
*/
void check_sequence_return(BS::thread_pool<>& pool, const std::int64_t random_start, const std::int64_t random_end)
{
logln("Verifying that submit_sequence() from ", random_start, " to ", random_end, " correctly sums all squares of indices...");
const auto sequence = [](const std::int64_t index)
{
return index * index;
};
const std::vector<std::int64_t> sums_vector = pool.submit_sequence(random_start, random_end, sequence).get();
std::int64_t sum = 0;
for (const std::int64_t partial_sum : sums_vector)
sum += partial_sum;
std::int64_t correct_sum = 0;
for (std::int64_t i = random_start; i < random_end; i++)
correct_sum += i * i;
check(correct_sum, sum);
}
/**
* @brief Check that detach_sequence() and submit_sequence() work using several different random values for the range of indices.
*/
void check_sequence()
{
constexpr std::int64_t range = 1000;
constexpr std::size_t repeats = 10;
BS::thread_pool pool;
for (std::size_t i = 0; i < repeats; ++i)
{
const std::pair<std::int64_t, std::int64_t> indices = random_pair(-range, range);
check(check_sequence_no_return(pool, indices.first, indices.second, "detach_sequence()"));
}
for (std::size_t i = 0; i < repeats; ++i)
{
const std::pair<std::int64_t, std::int64_t> indices = random_pair(-range, range);
check(check_sequence_no_return(pool, indices.first, indices.second, "submit_sequence()"));
}
for (std::size_t i = 0; i < repeats; ++i)
{
const std::pair<std::int64_t, std::int64_t> indices = random_pair(-range, range);
check_sequence_return(pool, indices.first, indices.second);
}
logln("Verifying that detach_sequence() with identical start and end indices does nothing...");
{
std::atomic<std::size_t> count = 0;
const std::int64_t index = random(-range, range);
logln("Range: ", index, " to ", index);
pool.detach_sequence(index, index,
[&count](const std::int64_t)
{
++count;
});
pool.wait();
check(count == 0);
}
logln("Verifying that submit_sequence() with identical start and end indices does nothing...");
{
std::atomic<std::size_t> count = 0;
const std::int64_t index = random(-range, range);
logln("Range: ", index, " to ", index);
pool.submit_sequence(index, index,
[&count](const std::int64_t)
{
++count;
})
.wait();
check(count == 0);
}
logln("Verifying that detach_sequence() with end index smaller than the start index does nothing...");
{
std::atomic<std::size_t> count = 0;
const std::pair<std::int64_t, std::int64_t> indices = random_pair(-range, range);
logln("Range: ", indices.second, " to ", indices.first);
pool.detach_sequence(indices.second, indices.first,
[&count](const std::int64_t)
{
++count;
});
pool.wait();
check(count == 0);
}
logln("Verifying that submit_sequence() with end index smaller than the start index does nothing...");
{
std::atomic<std::size_t> count = 0;
const std::pair<std::int64_t, std::int64_t> indices = random_pair(-range, range);
logln("Range: ", indices.second, " to ", indices.first);
pool.submit_sequence(indices.second, indices.first,
[&count](const std::int64_t)
{
++count;
})
.wait();
check(count == 0);
}
}
// ===============================================
// Functions to verify task monitoring and control
// ===============================================
/**
* @brief Check that task monitoring works.
*/
void check_task_monitoring()
{
constexpr std::chrono::milliseconds sleep_time(300);
const std::size_t num_threads = std::min<std::size_t>(std::thread::hardware_concurrency(), 4);
logln("Creating pool with ", num_threads, " threads.");
BS::thread_pool pool(num_threads);
logln("Submitting ", num_threads * 3, " tasks.");
counting_semaphore sem(0);
for (std::size_t i = 0; i < num_threads * 3; ++i)
{
pool.detach_task(
[i, &sem]
{
sem.acquire();
logln("Task ", i, " released.");
});
}
std::this_thread::sleep_for(sleep_time);
logln("After submission, should have: ", num_threads * 3, " tasks total, ", num_threads, " tasks running, ", num_threads * 2, " tasks queued...");
log("Result: ", pool.get_tasks_total(), " tasks total, ", pool.get_tasks_running(), " tasks running, ", pool.get_tasks_queued(), " tasks queued ");
check(pool.get_tasks_total() == num_threads * 3 && pool.get_tasks_running() == num_threads && pool.get_tasks_queued() == num_threads * 2);
sem.release(static_cast<std::ptrdiff_t>(num_threads));
std::this_thread::sleep_for(sleep_time);
logln("After releasing ", num_threads, " tasks, should have: ", num_threads * 2, " tasks total, ", num_threads, " tasks running, ", num_threads, " tasks queued...");
log("Result: ", pool.get_tasks_total(), " tasks total, ", pool.get_tasks_running(), " tasks running, ", pool.get_tasks_queued(), " tasks queued ");
check(pool.get_tasks_total() == num_threads * 2 && pool.get_tasks_running() == num_threads && pool.get_tasks_queued() == num_threads);
sem.release(static_cast<std::ptrdiff_t>(num_threads));
std::this_thread::sleep_for(sleep_time);
logln("After releasing ", num_threads, " more tasks, should have: ", num_threads, " tasks total, ", num_threads, " tasks running, ", 0, " tasks queued...");
log("Result: ", pool.get_tasks_total(), " tasks total, ", pool.get_tasks_running(), " tasks running, ", pool.get_tasks_queued(), " tasks queued ");
check(pool.get_tasks_total() == num_threads && pool.get_tasks_running() == num_threads && pool.get_tasks_queued() == 0);
sem.release(static_cast<std::ptrdiff_t>(num_threads));
std::this_thread::sleep_for(sleep_time);
logln("After releasing the final ", num_threads, " tasks, should have: ", 0, " tasks total, ", 0, " tasks running, ", 0, " tasks queued...");
log("Result: ", pool.get_tasks_total(), " tasks total, ", pool.get_tasks_running(), " tasks running, ", pool.get_tasks_queued(), " tasks queued ");
check(pool.get_tasks_total() == 0 && pool.get_tasks_running() == 0 && pool.get_tasks_queued() == 0);
}
/**
* @brief Check that pausing works.
*/
void check_pausing()
{
constexpr std::chrono::milliseconds sleep_time(200);
BS::pause_thread_pool pool;
logln("Checking that the pool correctly reports that it is not paused after construction...");
check(!pool.is_paused());
logln("Pausing pool.");
pool.pause();
logln("Checking that the pool correctly reports that it is paused...");
check(pool.is_paused());
logln("Submitting task and waiting.");
std::atomic<bool> flag = false;
pool.detach_task(
[&flag]
{
flag = true;
logln("Task executed.");
});
std::this_thread::sleep_for(sleep_time);
logln("Verifying that the task has not been executed...");
check(!flag);
logln("Unpausing pool and waiting.");
pool.unpause();
std::this_thread::sleep_for(sleep_time);
logln("Verifying that the task has been executed...");
check(flag);
logln("Checking that the pool correctly reports that it is not paused...");
check(!pool.is_paused());
}
/**
* @brief Check that purge() works.
*/
void check_purge()
{
constexpr std::chrono::milliseconds long_sleep_time(200);
constexpr std::chrono::milliseconds short_sleep_time(100);
constexpr std::size_t num_tasks = 10;
BS::thread_pool pool(1);
logln("Submitting ", num_tasks, " tasks to the pool.");
std::vector<std::atomic<bool>> flags(num_tasks);
for (std::size_t i = 0; i < num_tasks; ++i)
{
pool.detach_task(
[&flags, i, long_sleep_time]
{
std::this_thread::sleep_for(long_sleep_time);
logln("Task ", i, " done.");
flags[i] = true;
});
}
std::this_thread::sleep_for(short_sleep_time);
logln("Purging the pool and waiting for tasks...");
pool.purge();
pool.wait();
logln("Checking that only the first task was executed...");
flags[0] = !flags[0];
check(no_flags_set(flags));
}
#ifdef __cpp_exceptions
// ======================================
// Functions to verify exception handling
// ======================================
/**
* @brief An exception class to be thrown when testing exception handling.
*/
struct test_exception : public std::runtime_error
{
test_exception() : std::runtime_error("Exception thrown!") {};
};
/**
* @brief A function that throws a `test_exception`.
*/
void throws()
{
logln("Throwing exception...");
throw test_exception();
};
/**
* @brief Check that exceptions are forwarded correctly by submit_task().
*/
void check_exceptions_submit()
{
BS::thread_pool pool;
logln("Checking that exceptions are forwarded correctly by submit_task()...");
bool caught = false;
std::future<void> future = pool.submit_task(throws);
try
{
future.get();
}
catch (const test_exception&)
{
caught = true;
}
check(caught);
}
/**
* @brief Check that exceptions are forwarded correctly by `BS::multi_future`.
*/
void check_exceptions_multi_future()
{
BS::thread_pool pool;
logln("Checking that exceptions are forwarded correctly by BS::multi_future...");
bool caught = false;
BS::multi_future<void> future;
future.push_back(pool.submit_task(throws));
future.push_back(pool.submit_task(throws));
try
{
future.get();
}
catch (const test_exception&)
{
caught = true;
}
check(caught);
}
#endif
// =====================================
// Functions to verify vector operations
// =====================================
/**
* @brief Check that parallelized vector operations work as expected by calculating the sum of two randomized vectors of a specific size in two ways, single-threaded and multithreaded, and comparing the results.
*
* @param pool The thread pool to check.
* @param vector_size The size of the vectors.
* @param num_tasks The number of tasks to split the calculation into.
* @return `true` if the single-threaded and multithreaded results are equal, `false` otherwise.
*/
bool check_vector_of_size(BS::thread_pool<>& pool, const std::size_t vector_size, const std::size_t num_tasks)
{
constexpr std::int64_t value_range = 1000000;
std::vector<std::int64_t> vector_1(vector_size);
std::vector<std::int64_t> vector_2(vector_size);
for (std::size_t i = 0; i < vector_size; ++i)
{
vector_1[i] = random(-value_range, value_range);
vector_2[i] = random(-value_range, value_range);
}
logln("Adding two vectors with ", vector_size, " elements using ", num_tasks, " tasks...");
std::vector<std::int64_t> sum_single(vector_size);
for (std::size_t i = 0; i < vector_size; ++i)
sum_single[i] = vector_1[i] + vector_2[i];
std::vector<std::int64_t> sum_multi(vector_size);
pool.submit_blocks(
0, vector_size,
[&sum_multi, &vector_1, &vector_2](const std::size_t start, const std::size_t end)
{
for (std::size_t i = start; i < end; ++i)
sum_multi[i] = vector_1[i] + vector_2[i];
},
num_tasks)
.wait();
for (std::size_t i = 0; i < vector_size; ++i)
{
if (sum_single[i] != sum_multi[i])
return false;
}
return true;
}
/**
* @brief Check that parallelized vector operations work as expected.
*/
void check_vectors()
{
constexpr std::size_t size_range = 1000000;
constexpr std::size_t repeats = 10;
BS::thread_pool pool;
for (std::size_t i = 0; i < repeats; ++i)
check(check_vector_of_size(pool, random<std::size_t>(0, size_range), random<std::size_t>(1, pool.get_thread_count())));
}
// =================================
// Functions to verify task priority
// =================================
// Priorities are 8-bit integers, but `std::uniform_int_distribution` needs at least a 16-bit integer.
using rand_priority_t = std::int16_t;
/**
* @brief Check that task priority works as expected with all task submission methods.
*/
void check_priority()
{
constexpr std::chrono::milliseconds sleep_time(200);
constexpr std::size_t num_tasks = 10;
// Set the pool to have only 1 thread, so it can only run 1 task at a time. This will ensure the tasks will be executed in priority order.
BS::thread_pool<BS::tp::priority | BS::tp::pause> pool(1);
pool.pause();
// Create a shuffled list of priorities.
std::vector<BS::priority_t> priorities;
priorities.reserve(num_tasks - 1);
for (std::size_t i = 0; i < num_tasks - 1; ++i)
priorities.push_back(static_cast<BS::priority_t>((i % 2 == 0) ? random<rand_priority_t>(0, BS::pr::highest) : random<rand_priority_t>(BS::pr::lowest, 0)));
priorities.push_back(BS::pr::lowest);
priorities.push_back(0);
priorities.push_back(BS::pr::highest);
std::shuffle(priorities.begin(), priorities.end(), std::mt19937_64(std::random_device()()));
// Submit tasks using various methods in random priority order.
std::vector<BS::priority_t> execution_order;
std::mutex exec_mutex;
const auto execute_task_priority = [&execution_order, &exec_mutex](const BS::priority_t priority)
{
const std::scoped_lock lock(exec_mutex);
logln("Task with priority ", static_cast<rand_priority_t>(priority), " executed.");
execution_order.push_back(priority);
};
const std::vector<std::string_view> functions = {"detach_task", "submit_task", "detach_sequence", "submit_sequence", "detach_loop", "submit_loop", "detach_blocks", "submit_blocks"};
for (const BS::priority_t priority : priorities)
{
const std::string_view func = functions[random<std::size_t>(0, functions.size() - 1)];
logln("Launching ", func, "() with priority ", static_cast<rand_priority_t>(priority), "...");
if (func == "detach_task")
{
pool.detach_task(
[priority, &execute_task_priority]
{
execute_task_priority(priority);
},
priority);
}
else if (func == "submit_task")
{
std::ignore = pool.submit_task(
[priority, &execute_task_priority]
{
execute_task_priority(priority);
},
priority);
}
else if (func == "detach_sequence")
{
pool.detach_sequence(
0, 1,
[priority, &execute_task_priority](std::int64_t)
{
execute_task_priority(priority);
},
priority);
}
else if (func == "submit_sequence")
{
std::ignore = pool.submit_sequence(
0, 1,
[priority, &execute_task_priority](std::int64_t)
{
execute_task_priority(priority);
},
priority);
}
else if (func == "detach_loop")
{
pool.detach_loop(
0, 1,
[priority, &execute_task_priority](std::int64_t)
{
execute_task_priority(priority);
},
0, priority);
}
else if (func == "submit_loop")
{
std::ignore = pool.submit_loop(
0, 1,
[priority, &execute_task_priority](std::int64_t)
{
execute_task_priority(priority);
},
0, priority);
}
else if (func == "detach_blocks")
{
pool.detach_blocks(
0, 1,
[priority, &execute_task_priority](std::int64_t, std::int64_t)
{
execute_task_priority(priority);
},
0, priority);
}
else if (func == "submit_blocks")
{
std::ignore = pool.submit_blocks(
0, 1,
[priority, &execute_task_priority](std::int64_t, std::int64_t)
{
execute_task_priority(priority);
},
0, priority);
}
}
// Unpause the pool so the tasks can be executed, then check that they were executed in the correct order.
logln("Checking execution order...");
std::this_thread::sleep_for(sleep_time);
pool.unpause();
pool.wait();
std::sort(priorities.rbegin(), priorities.rend());
check(execution_order == priorities);
}
// =======================================================================
// Functions to verify thread initialization, cleanup, and BS::this_thread
// =======================================================================
/**
* @brief Check that thread initialization functions and get_index() work.
*/
void check_init()
{
logln("Comparing thread indices reported by get_index() using an initialization function passed to reset():");
std::vector<std::atomic<std::size_t>> thread_indices(std::thread::hardware_concurrency());
std::atomic<bool> correct = true;
BS::thread_pool pool;
pool.reset(
[&thread_indices, &correct](std::size_t idx)
{
const std::optional<std::size_t> reported_idx = BS::this_thread::get_index();
if (reported_idx.has_value())
thread_indices[idx] = reported_idx.value();
else
correct = false;
});
pool.wait();
logln("Checking that all reported indices have values...");
check(correct);
correct = true;
for (std::size_t i = 0; i < thread_indices.size(); ++i)
{
if (thread_indices[i] != i)
{
correct = false;
break;
}
}
logln("Checking that all reported indices are correct...");
check(correct);
logln("Verifying that the index of the main thread has no value...");
const std::optional<std::size_t> main_idx = BS::this_thread::get_index();
check(!main_idx.has_value());
logln("Verifying that the index of an independent thread has no value...");
std::thread test_thread(
[]
{
const std::optional<std::size_t> ind_idx = BS::this_thread::get_index();
check(!ind_idx.has_value());
});
test_thread.join();
}
/**
* @brief Check that thread cleanup functions work.
*/
void check_cleanup()
{
logln("Comparing thread indices reported by get_index() using a cleanup function passed to set_cleanup_func():");
std::vector<std::atomic<std::size_t>> thread_indices(std::thread::hardware_concurrency());
std::atomic<bool> correct = true;
{
BS::thread_pool pool;
pool.set_cleanup_func(
[&thread_indices, &correct](std::size_t idx)
{
const std::optional<std::size_t> reported_idx = BS::this_thread::get_index();
if (reported_idx.has_value())
thread_indices[idx] = reported_idx.value();
else
correct = false;
});
}
logln("Checking that all reported indices have values...");
check(correct);
correct = true;
for (std::size_t i = 0; i < thread_indices.size(); ++i)
{
if (thread_indices[i] != i)
{
correct = false;
break;
}
}
logln("Checking that all reported indices are correct...");
check(correct);
}
/**
* @brief Check that get_pool() works.
*/
void check_get_pool()
{
logln("Checking that all threads report the correct pool...");
std::vector<std::atomic<void*>> thread_pool_ptrs1(std::thread::hardware_concurrency());
std::vector<std::atomic<void*>> thread_pool_ptrs2(std::thread::hardware_concurrency());
const auto store_pointers = [](std::vector<std::atomic<void*>>& ptrs)
{
const auto ptr = BS::this_thread::get_pool();
if (ptr.has_value())
ptrs[*BS::this_thread::get_index()] = *ptr;
else
check(false);
};
BS::thread_pool pool1(
[&thread_pool_ptrs1, &store_pointers]
{
store_pointers(thread_pool_ptrs1);
});
BS::thread_pool pool2(
[&thread_pool_ptrs2, &store_pointers]
{
store_pointers(thread_pool_ptrs2);
});
pool1.wait();
pool2.wait();
const auto check_pointers = [](const std::vector<std::atomic<void*>>& ptrs, const BS::thread_pool<>& pool)
{
check(all_flags_equal(ptrs, (void*)&pool));
};
check_pointers(thread_pool_ptrs1, pool1);
check_pointers(thread_pool_ptrs2, pool2);
{
logln("Verifying that the pool pointer of the main thread has no value...");
const auto ptr = BS::this_thread::get_pool();
check(!ptr.has_value());
}
{
logln("Verifying that the pool pointer of an independent thread has no value...");
std::thread test_thread(
[]
{
const auto ptr = BS::this_thread::get_pool();
check(!ptr.has_value());
});
test_thread.join();
}
}
// =========================================================
// Functions to verify proper handling of parallelized tasks
// =========================================================
/**
* @brief A class used to count how many times the copy and move constructors have been invoked since the creation of the initial object.
*/
class [[nodiscard]] count_copy_move
{
public:
count_copy_move(std::atomic<std::size_t>* copied_, std::atomic<std::size_t>* moved_) : copied(copied_), moved(moved_) {}
count_copy_move(const count_copy_move& other) : copied(other.copied), moved(other.moved)
{
++(*copied);
}
count_copy_move(count_copy_move&& other) noexcept : copied(other.copied), moved(other.moved)
{
++(*moved);
}
count_copy_move& operator=(const count_copy_move&) = delete;
count_copy_move& operator=(count_copy_move&&) = delete;
~count_copy_move() = default;
private:
std::atomic<std::size_t>* copied = nullptr;
std::atomic<std::size_t>* moved = nullptr;
}; // class count_copy_move
/**
* @brief Check, for a specific member function which parallelizes loops or sequences of tasks, that the callable object does not get copied in the process.
*
* @param which_func A string naming the function to check.
*/
void check_copy(const std::string_view which_func)
{
BS::thread_pool pool;
const std::size_t num_tasks = pool.get_thread_count() * 10;
logln("Checking ", which_func, "...");
std::atomic<std::size_t> copied = 0;
std::atomic<std::size_t> moved = 0;
auto task = [detect = count_copy_move(&copied, &moved)](auto&&...) {};
if (which_func == "detach_blocks()")
pool.detach_blocks(0, num_tasks, std::move(task), num_tasks);
else if (which_func == "detach_loop()")
pool.detach_loop(0, num_tasks, std::move(task));
else if (which_func == "detach_sequence()")
pool.detach_sequence(0, num_tasks, std::move(task));
else if (which_func == "submit_blocks()")
std::ignore = pool.submit_blocks(0, num_tasks, std::move(task), num_tasks);
else if (which_func == "submit_loop()")
std::ignore = pool.submit_loop(0, num_tasks, std::move(task));
else if (which_func == "submit_sequence()")
std::ignore = pool.submit_sequence(0, num_tasks, std::move(task));
pool.wait();
logln("Copy count: ");
check(0, copied.load()); // Note: Move count will be unpredictable if priority is on, so we don't check it.
}
/**
* @brief Check, for all member functions which parallelize loops or sequences of tasks, that the callable object does not get copied in the process.
*/
void check_copy_all()
{
check_copy("detach_blocks()");
check_copy("detach_loop()");
check_copy("detach_sequence()");
check_copy("submit_blocks()");
check_copy("submit_loop()");
check_copy("submit_sequence()");
}
/**
* @brief A class used to detect if an object was destructed prematurely.
*/
class detect_destruct
{
public:
explicit detect_destruct(std::atomic<bool>* object_exists_) : object_exists(object_exists_)
{
*object_exists = true;
};
detect_destruct(const detect_destruct&) = delete;
detect_destruct(detect_destruct&&) noexcept = delete;
detect_destruct& operator=(const detect_destruct&) = delete;
detect_destruct& operator=(detect_destruct&&) = delete;
~detect_destruct()
{
*object_exists = false;
};
private:
std::atomic<bool>* object_exists = nullptr;
};
/**
* @brief Check, for a specific member function which parallelizes loops or sequences of tasks, that if a task that captures a shared pointer is submitted, the pointer is correctly shared between all the iterations of the task.
*
* @param which_func A string naming the function to check.
*/
void check_shared_ptr(const std::string_view which_func)
{
BS::thread_pool pool;
constexpr std::chrono::milliseconds sleep_time(10);
const std::size_t num_tasks = pool.get_thread_count() * 10;
std::atomic<bool> object_exists = false;
std::atomic<std::size_t> uses_before_destruct = 0;
std::atomic<std::size_t> uses_after_destruct = 0;
logln("Checking ", which_func, "...");
{
std::shared_ptr<detect_destruct> ptr = std::make_shared<detect_destruct>(&object_exists);
auto task = [ptr, &object_exists, &uses_before_destruct, &uses_after_destruct, &sleep_time](auto&&...)
{
std::this_thread::sleep_for(sleep_time);
if (object_exists)
++uses_before_destruct;
else
++uses_after_destruct;
};
if (which_func == "detach_blocks()")
pool.detach_blocks(0, num_tasks, std::move(task), num_tasks);
else if (which_func == "detach_loop()")
pool.detach_loop(0, num_tasks, std::move(task));
else if (which_func == "detach_sequence()")
pool.detach_sequence(0, num_tasks, std::move(task));
else if (which_func == "submit_blocks()")
std::ignore = pool.submit_blocks(0, num_tasks, std::move(task), num_tasks);
else if (which_func == "submit_loop()")
std::ignore = pool.submit_loop(0, num_tasks, std::move(task));
else if (which_func == "submit_sequence()")
std::ignore = pool.submit_sequence(0, num_tasks, std::move(task));
ptr.reset();
}
pool.wait();
std::this_thread::sleep_for(sleep_time);
logln("Uses before destruct:");
check(num_tasks, uses_before_destruct.load());
logln("Uses after destruct:");
check(0, uses_after_destruct.load());
}
/**
* @brief Check, for all member functions which parallelize loops or sequences of tasks, that if a task that captures a shared pointer is submitted, the pointer is correctly shared between all the iterations of the task.
*/
void check_shared_ptr_all()
{
check_shared_ptr("detach_blocks()");
check_shared_ptr("detach_loop()");
check_shared_ptr("detach_sequence()");
check_shared_ptr("submit_blocks()");
check_shared_ptr("submit_loop()");
check_shared_ptr("submit_sequence()");
}
/**
* @brief Check that a task is destructed immediately after it executes, and therefore does not artificially extend the lifetime of any captured objects.
*/
void check_task_destruct()
{
constexpr std::chrono::milliseconds sleep_time(20);
BS::thread_pool pool;
std::atomic<bool> object_exists = false;
{
const std::shared_ptr<detect_destruct> ptr = std::make_shared<detect_destruct>(&object_exists);
pool.submit_task([ptr] {}).wait();
}
std::this_thread::sleep_for(sleep_time);
check(!object_exists);
}
/**
* @brief Check that the type trait `BS::common_index_type` works as expected.
*/
void check_common_index_type()
{
// NOLINTBEGIN(misc-redundant-expression)
logln("Checking std::int8_t...");
check(std::is_same_v<BS::common_index_type_t<std::int8_t, std::int8_t>, std::int8_t> && std::is_same_v<BS::common_index_type_t<std::int8_t, std::int16_t>, std::int16_t> && std::is_same_v<BS::common_index_type_t<std::int8_t, std::int32_t>, std::int32_t> && std::is_same_v<BS::common_index_type_t<std::int8_t, std::int64_t>, std::int64_t> && std::is_same_v<BS::common_index_type_t<std::int8_t, std::uint8_t>, std::int16_t> && std::is_same_v<BS::common_index_type_t<std::int8_t, std::uint16_t>, std::int32_t> && std::is_same_v<BS::common_index_type_t<std::int8_t, std::uint32_t>, std::int64_t> && std::is_same_v<BS::common_index_type_t<std::int8_t, std::uint64_t>, std::uint64_t>);
logln("Checking std::int16_t...");
check(std::is_same_v<BS::common_index_type_t<std::int16_t, std::int8_t>, std::int16_t> && std::is_same_v<BS::common_index_type_t<std::int16_t, std::int16_t>, std::int16_t> && std::is_same_v<BS::common_index_type_t<std::int16_t, std::int32_t>, std::int32_t> && std::is_same_v<BS::common_index_type_t<std::int16_t, std::int64_t>, std::int64_t> && std::is_same_v<BS::common_index_type_t<std::int16_t, std::uint8_t>, std::int16_t> && std::is_same_v<BS::common_index_type_t<std::int16_t, std::uint16_t>, std::int32_t> && std::is_same_v<BS::common_index_type_t<std::int16_t, std::uint32_t>, std::int64_t> && std::is_same_v<BS::common_index_type_t<std::int16_t, std::uint64_t>, std::uint64_t>);
logln("Checking std::int32_t...");
check(std::is_same_v<BS::common_index_type_t<std::int32_t, std::int8_t>, std::int32_t> && std::is_same_v<BS::common_index_type_t<std::int32_t, std::int16_t>, std::int32_t> && std::is_same_v<BS::common_index_type_t<std::int32_t, std::int32_t>, std::int32_t> && std::is_same_v<BS::common_index_type_t<std::int32_t, std::int64_t>, std::int64_t> && std::is_same_v<BS::common_index_type_t<std::int32_t, std::uint8_t>, std::int32_t> && std::is_same_v<BS::common_index_type_t<std::int32_t, std::uint16_t>, std::int32_t> && std::is_same_v<BS::common_index_type_t<std::int32_t, std::uint32_t>, std::int64_t> && std::is_same_v<BS::common_index_type_t<std::int32_t, std::uint64_t>, std::uint64_t>);
logln("Checking std::int64_t...");
check(std::is_same_v<BS::common_index_type_t<std::int64_t, std::int8_t>, std::int64_t> && std::is_same_v<BS::common_index_type_t<std::int64_t, std::int16_t>, std::int64_t> && std::is_same_v<BS::common_index_type_t<std::int64_t, std::int32_t>, std::int64_t> && std::is_same_v<BS::common_index_type_t<std::int64_t, std::int64_t>, std::int64_t> && std::is_same_v<BS::common_index_type_t<std::int64_t, std::uint8_t>, std::int64_t> && std::is_same_v<BS::common_index_type_t<std::int64_t, std::uint16_t>, std::int64_t> && std::is_same_v<BS::common_index_type_t<std::int64_t, std::uint32_t>, std::int64_t> && std::is_same_v<BS::common_index_type_t<std::int64_t, std::uint64_t>, std::uint64_t>);
logln("Checking std::uint8_t...");
check(std::is_same_v<BS::common_index_type_t<std::uint8_t, std::int8_t>, std::int16_t> && std::is_same_v<BS::common_index_type_t<std::uint8_t, std::int16_t>, std::int16_t> && std::is_same_v<BS::common_index_type_t<std::uint8_t, std::int32_t>, std::int32_t> && std::is_same_v<BS::common_index_type_t<std::uint8_t, std::int64_t>, std::int64_t> && std::is_same_v<BS::common_index_type_t<std::uint8_t, std::uint8_t>, std::uint8_t> && std::is_same_v<BS::common_index_type_t<std::uint8_t, std::uint16_t>, std::uint16_t> && std::is_same_v<BS::common_index_type_t<std::uint8_t, std::uint32_t>, std::uint32_t> && std::is_same_v<BS::common_index_type_t<std::uint8_t, std::uint64_t>, std::uint64_t>);
logln("Checking std::uint16_t...");
check(std::is_same_v<BS::common_index_type_t<std::uint16_t, std::int8_t>, std::int32_t> && std::is_same_v<BS::common_index_type_t<std::uint16_t, std::int16_t>, std::int32_t> && std::is_same_v<BS::common_index_type_t<std::uint16_t, std::int32_t>, std::int32_t> && std::is_same_v<BS::common_index_type_t<std::uint16_t, std::int64_t>, std::int64_t> && std::is_same_v<BS::common_index_type_t<std::uint16_t, std::uint8_t>, std::uint16_t> && std::is_same_v<BS::common_index_type_t<std::uint16_t, std::uint16_t>, std::uint16_t> && std::is_same_v<BS::common_index_type_t<std::uint16_t, std::uint32_t>, std::uint32_t> && std::is_same_v<BS::common_index_type_t<std::uint16_t, std::uint64_t>, std::uint64_t>);
logln("Checking std::uint32_t...");
check(std::is_same_v<BS::common_index_type_t<std::uint32_t, std::int8_t>, std::int64_t> && std::is_same_v<BS::common_index_type_t<std::uint32_t, std::int16_t>, std::int64_t> && std::is_same_v<BS::common_index_type_t<std::uint32_t, std::int32_t>, std::int64_t> && std::is_same_v<BS::common_index_type_t<std::uint32_t, std::int64_t>, std::int64_t> && std::is_same_v<BS::common_index_type_t<std::uint32_t, std::uint8_t>, std::uint32_t> && std::is_same_v<BS::common_index_type_t<std::uint32_t, std::uint16_t>, std::uint32_t> && std::is_same_v<BS::common_index_type_t<std::uint32_t, std::uint32_t>, std::uint32_t> && std::is_same_v<BS::common_index_type_t<std::uint32_t, std::uint64_t>, std::uint64_t>);
logln("Checking std::uint64_t...");
check(std::is_same_v<BS::common_index_type_t<std::uint64_t, std::int8_t>, std::uint64_t> && std::is_same_v<BS::common_index_type_t<std::uint64_t, std::int16_t>, std::uint64_t> && std::is_same_v<BS::common_index_type_t<std::uint64_t, std::int32_t>, std::uint64_t> && std::is_same_v<BS::common_index_type_t<std::uint64_t, std::int64_t>, std::uint64_t> && std::is_same_v<BS::common_index_type_t<std::uint64_t, std::uint8_t>, std::uint64_t> && std::is_same_v<BS::common_index_type_t<std::uint64_t, std::uint16_t>, std::uint64_t> && std::is_same_v<BS::common_index_type_t<std::uint64_t, std::uint32_t>, std::uint64_t> && std::is_same_v<BS::common_index_type_t<std::uint64_t, std::uint64_t>, std::uint64_t>);
// NOLINTEND(misc-redundant-expression)
}
// ================================
// Functions to check for deadlocks
// ================================
// An auxiliary thread pool used by check_deadlock(). It's a global variable so that the program will not get stuck upon destruction of this pool if a deadlock actually occurs.
BS::thread_pool check_deadlock_pool;
/**
* @brief Check that the specified function does not create deadlocks. The function will be run many times to increase the probability of encountering a deadlock as a result of subtle timing issues. Uses an auxiliary pool so the whole test doesn't get stuck if a deadlock is encountered.
*
* @tparam F The type of the function.
* @param task The function to try.
*/
template <typename F>
void check_deadlock(const F&& task)
{
constexpr std::chrono::milliseconds sleep_time(200);
constexpr std::size_t tries = 10000;
std::size_t try_n = 0;
check_deadlock_pool.detach_task(
[&try_n, &task]
{
do
task();
while (++try_n < tries);
});
bool passed = false;
while (true)
{
const std::size_t old_try_n = try_n;
check_deadlock_pool.wait_for(sleep_time);
if (try_n == tries)
{
logln_ansi(ansi_success, "Successfully finished all tries!");
passed = true;
break;
}
if (try_n == old_try_n)
{
logln_ansi(ansi_error, "Error: deadlock detected!");
passed = false;
break;
}
logln("Finished ", try_n, " tries out of ", tries, "...");
}
check(passed);
}
#ifdef BS_THREAD_POOL_NATIVE_EXTENSIONS
// ====================================
// Functions to check native extensions
// ====================================
/**
* @brief A map between pre-defined OS process priorities and their string representations.
*/
const std::map<BS::os_process_priority, std::string> os_process_priority_map = {{BS::os_process_priority::idle, "idle"}, {BS::os_process_priority::below_normal, "below_normal"}, {BS::os_process_priority::normal, "normal"}, {BS::os_process_priority::above_normal, "above_normal"}, {BS::os_process_priority::high, "high"}, {BS::os_process_priority::realtime, "realtime"}};
/**
* @brief Get the string representation of an OS process priority.
*
* @param priority A `std::optional<BS::os_process_priority>` object.
* @return A string containing the name of the priority, or "unknown" if the priority is not recognized, or "N/A" if the optional value is not set.
*/
std::string os_process_priority_name(const std::optional<BS::os_process_priority>& priority)
{
if (priority.has_value())
{
const std::map<BS::os_process_priority, std::string>::const_iterator it = os_process_priority_map.find(*priority);
return (it != os_process_priority_map.end()) ? it->second : "unknown";
}
return "N/A";
}
/**
* @brief A map between pre-defined OS thread priorities and their string representations.
*/
const std::map<BS::os_thread_priority, std::string> os_thread_priority_map = {{BS::os_thread_priority::idle, "idle"}, {BS::os_thread_priority::lowest, "lowest"}, {BS::os_thread_priority::below_normal, "below_normal"}, {BS::os_thread_priority::normal, "normal"}, {BS::os_thread_priority::above_normal, "above_normal"}, {BS::os_thread_priority::highest, "highest"}, {BS::os_thread_priority::realtime, "realtime"}};
/**
* @brief Get the string representation of an OS thread priority.
*
* @param priority A `std::optional<BS::os_thread_priority>` object.
* @return A string containing the name of the priority, or "unknown" if the priority is not recognized, or "N/A" if the optional value is not set.
*/
std::string os_thread_priority_name(const std::optional<BS::os_thread_priority>& priority)
{
if (priority.has_value())
{
const std::map<BS::os_thread_priority, std::string>::const_iterator it = os_thread_priority_map.find(*priority);
return (it != os_thread_priority_map.end()) ? it->second : "unknown";
}
return "N/A";
}
/**
* @brief Check if a condition is met, report the result, but do not keep count of the total number of successes and failures, because failure is expected if the test is not run as root.
*
* @param condition The condition to check.
*/
void check_root(const bool condition)
{
if (condition)
{
logln("-> passed.");
++test_results::tests_succeeded;
}
else
{
logln("-> failed, most likely due to insufficient permissions; ignoring.");
}
}
/**
* @brief Check if the expected result has been obtained, report the result, but do not keep count of the total number of successes and failures, because failure is expected if the test is not run as root.
*
* @param expected The expected result.
* @param obtained The obtained result.
*/
template <typename T1, typename T2>
void check_root(const T1& expected, const T2& obtained)
{
log("- Expected: ", expected, ", obtained: ", obtained, ' ');
check_root(expected == static_cast<T1>(obtained));
}
/**
* @brief Check that getting and setting OS process priorities works.
*/
void check_os_process_priorities()
{
logln("Checking OS process priorities...");
logln_ansi(ansi_info, "NOTE: This test must be run as admin/root, otherwise it will fail!");
// We go over the priorities in reverse order because on Linux, a non-root user can only decrease the priority, so if we start from the lowest priority, all tests will fail except the first one.
const std::vector<BS::os_process_priority> priorities = {BS::os_process_priority::realtime, BS::os_process_priority::high, BS::os_process_priority::above_normal, BS::os_process_priority::normal, BS::os_process_priority::below_normal, BS::os_process_priority::idle};
for (BS::os_process_priority priority : priorities)
{
log("Setting OS process priority to ", os_process_priority_name(priority), ' ');
// On Windows we should be able to set all the priorities even as non-admin; realtime will "succeed" but actually set the priority to high. On Linux, only root can increase the priority beyond normal.
#ifdef _WIN32
check(BS::set_os_process_priority(priority));
#else
if (priority >= BS::os_process_priority::normal)
check(BS::set_os_process_priority(priority));
else
check_root(BS::set_os_process_priority(priority));
#endif
const std::optional<BS::os_process_priority> new_priority = BS::get_os_process_priority();
log("Obtaining new OS process priority ");
check(new_priority.has_value());
#ifdef _WIN32
if (priority != BS::os_process_priority::realtime)
check(os_process_priority_name(priority), os_process_priority_name(new_priority));
else
check_root(os_process_priority_name(priority), os_process_priority_name(new_priority));
#else
if (priority >= BS::os_process_priority::normal)
check(os_process_priority_name(priority), os_process_priority_name(new_priority));
else
check_root(os_process_priority_name(priority), os_process_priority_name(new_priority));
#endif
}
// Set the priority back to normal after the test ends. This will fail on Linux if not root.
logln("Setting priority back to normal...");
#ifdef _WIN32
check(BS::set_os_process_priority(BS::os_process_priority::normal));
#else
check_root(BS::set_os_process_priority(BS::os_process_priority::normal));
#endif
}
/**
* @brief Check that getting and setting OS thread priorities works.
*/
void check_os_thread_priorities()
{
BS::thread_pool pool;
pool.detach_task(
[]
{
logln("Checking OS thread priorities for pool threads...");
#ifdef __linux__
logln_ansi(ansi_info, "NOTE: On Linux, this test must be run as root, otherwise it will fail!");
#endif
const std::vector<BS::os_thread_priority> priorities = {BS::os_thread_priority::realtime, BS::os_thread_priority::highest, BS::os_thread_priority::above_normal, BS::os_thread_priority::normal, BS::os_thread_priority::below_normal, BS::os_thread_priority::lowest, BS::os_thread_priority::idle};
for (BS::os_thread_priority priority : priorities)
{
log("Setting OS thread priority to ", os_thread_priority_name(priority), ' ');
// On Windows we should be able to set all the priorities even as non-admin, including realtime. On Linux, only root can increase the priority beyond normal. (Also, note that on WSL, even root cannot set the priority to highest or above.)
#ifdef _WIN32
check(BS::this_thread::set_os_thread_priority(priority));
#else
if (priority <= BS::os_thread_priority::normal)
check(BS::this_thread::set_os_thread_priority(priority));
else
check_root(BS::this_thread::set_os_thread_priority(priority));
#endif
const std::optional<BS::os_thread_priority> new_priority = BS::this_thread::get_os_thread_priority();
log("Obtaining new OS thread priority ");
check(new_priority.has_value());
#ifdef _WIN32
check(os_thread_priority_name(priority), os_thread_priority_name(new_priority));
#else
check_root(os_thread_priority_name(priority), os_thread_priority_name(new_priority));
#endif
}
// Set the priority back to normal after the test ends. This will fail on Linux/macOS if not running as root.
logln("Setting priority back to normal...");
#ifdef _WIN32
check(BS::this_thread::set_os_thread_priority(BS::os_thread_priority::normal));
#else
check_root(BS::this_thread::set_os_thread_priority(BS::os_thread_priority::normal));
#endif
});
}
/**
* @brief Check that getting and setting OS thread names works.
*/
void check_os_thread_names()
{
logln("Checking OS thread names...");
const std::string name = "BS_thread_pool";
logln("Setting main thread name to \"", name, "\"...");
check(BS::this_thread::set_os_thread_name(name));
logln("Obtaining new OS thread name...");
std::optional<std::string> new_name = BS::this_thread::get_os_thread_name();
if (new_name.has_value())
{
check(true);
check(name, *new_name);
}
else
{
check(false);
}
}
#if defined(_WIN32) || defined(__linux__)
/**
* @brief Convert a `std::vector<bool>` representing CPU affinity to a string of 0s and 1s.
*
* @param affinity The affinity.
* @return The string.
*/
std::string affinity_to_string(const std::optional<std::vector<bool>>& affinity)
{
if (affinity.has_value())
{
const std::size_t num_bits = affinity->size();
std::string str(num_bits, ' ');
for (std::size_t i = 0; i < num_bits; ++i)
str[num_bits - i - 1] = (*affinity)[i] ? '1' : '0';
return str;
}
return "N/A";
}
/**
* @brief Check that getting and setting OS process affinity works.
*/
void check_os_process_affinity()
{
logln("Checking OS process affinity...");
log("Obtaining initial process affinity ");
const std::optional<std::vector<bool>> initial_affinity = BS::get_os_process_affinity();
check(initial_affinity.has_value());
logln("Initial affinity is: ", affinity_to_string(initial_affinity));
const std::size_t num_bits = initial_affinity.has_value() ? initial_affinity->size() : std::thread::hardware_concurrency();
log("Setting affinity to CPU 1 only ");
std::vector<bool> cpu_1_in(num_bits, false);
cpu_1_in[0] = true;
check(BS::set_os_process_affinity(cpu_1_in));
log("Obtaining new affinity ");
const std::optional<std::vector<bool>> cpu_1_out = BS::get_os_process_affinity();
check(cpu_1_out.has_value());
check(affinity_to_string(cpu_1_in), affinity_to_string(cpu_1_out));
log("Setting affinity to alternating CPUs ");
std::vector<bool> alternating_in(num_bits, false);
for (std::size_t i = 0; i < num_bits; ++i)
alternating_in[i] = (i % 2 == 1);
check(BS::set_os_process_affinity(alternating_in));
log("Obtaining new affinity ");
const std::optional<std::vector<bool>> alternating_out = BS::get_os_process_affinity();
check(alternating_out.has_value());
check(affinity_to_string(alternating_in), affinity_to_string(alternating_out));
if (initial_affinity.has_value())
{
log("Setting affinity back to initial value ");
check(BS::set_os_process_affinity(*initial_affinity));
log("Obtaining new affinity ");
const std::optional<std::vector<bool>> initial_out = BS::get_os_process_affinity();
check(initial_out.has_value());
check(affinity_to_string(initial_affinity), affinity_to_string(initial_out));
}
}
/**
* @brief Check that getting and setting OS thread affinity works.
*/
void check_os_thread_affinity()
{
BS::thread_pool pool;
pool.detach_task(
[]
{
// Since the thread affinity must be a subset of the process affinity, we first set its affinity to all CPUs if it wasn't already.
const std::optional<std::vector<bool>> initial_process_affinity = BS::get_os_process_affinity();
const std::size_t num_process_bits = initial_process_affinity.has_value() ? initial_process_affinity->size() : std::thread::hardware_concurrency();
const std::vector<bool> all_enabled(num_process_bits, true);
BS::set_os_process_affinity(all_enabled);
logln("Checking OS thread affinity for pool threads...");
log("Obtaining initial thread affinity ");
const std::optional<std::vector<bool>> initial_affinity = BS::this_thread::get_os_thread_affinity();
check(initial_affinity.has_value());
logln("Initial affinity is: ", affinity_to_string(initial_affinity));
const std::size_t num_bits = initial_affinity.has_value() ? initial_affinity->size() : std::thread::hardware_concurrency();
log("Setting affinity to CPU 1 only ");
std::vector<bool> cpu_1_in(num_bits, false);
cpu_1_in[0] = true;
check(BS::this_thread::set_os_thread_affinity(cpu_1_in));
log("Obtaining new affinity ");
const std::optional<std::vector<bool>> cpu_1_out = BS::this_thread::get_os_thread_affinity();
check(cpu_1_out.has_value());
check(affinity_to_string(cpu_1_in), affinity_to_string(cpu_1_out));
log("Setting affinity to alternating CPUs ");
std::vector<bool> alternating_in(num_bits, false);
for (std::size_t i = 0; i < num_bits; ++i)
alternating_in[i] = (i % 2 == 1);
check(BS::this_thread::set_os_thread_affinity(alternating_in));
log("Obtaining new affinity ");
const std::optional<std::vector<bool>> alternating_out = BS::this_thread::get_os_thread_affinity();
check(alternating_out.has_value());
check(affinity_to_string(alternating_in), affinity_to_string(alternating_out));
if (initial_affinity.has_value())
{
log("Setting affinity back to initial value ");
check(BS::this_thread::set_os_thread_affinity(*initial_affinity));
log("Obtaining new affinity ");
const std::optional<std::vector<bool>> initial_out = BS::this_thread::get_os_thread_affinity();
check(initial_out.has_value());
check(affinity_to_string(initial_affinity), affinity_to_string(initial_out));
}
if (initial_process_affinity.has_value())
BS::set_os_process_affinity(*initial_process_affinity);
});
}
#endif
/**
* @brief Try to set the OS priority of this thread to the highest possible value. Also set the name of the thread for debugging purposes.
*/
void try_os_thread_priority()
{
if (!BS::this_thread::set_os_thread_priority(BS::os_thread_priority::realtime))
if (!BS::this_thread::set_os_thread_priority(BS::os_thread_priority::highest))
BS::this_thread::set_os_thread_priority(BS::os_thread_priority::above_normal);
std::optional<std::size_t> idx = BS::this_thread::get_index();
if (idx.has_value())
BS::this_thread::set_os_thread_name(make_string("Benchmark #", *idx));
else
BS::this_thread::set_os_thread_name("Benchmark main");
}
#endif
// ========================
// Functions for benchmarks
// ========================
/**
* @brief A struct to store the mean and standard deviation of the results of a test.
*/
struct [[nodiscard]] mean_sd
{
mean_sd(const double mean_, const double sd_) : mean(mean_), sd(sd_) {}
double mean = 0;
double sd = 0;
};
/**
* @brief Print the timing of a specific test.
*
* @param stats A struct containing the mean and standard deviation.
* @param pixels_per_ms The number of pixels per millisecond.
*/
void print_timing(const mean_sd& stats, const double pixels_per_ms)
{
constexpr int width_mean = 6;
constexpr int width_sd = 4;
constexpr int width_pms = 7;
logln("-> Mean: ", std::setw(width_mean), stats.mean, " ms, standard deviation: ", std::setw(width_sd), stats.sd, " ms, speed: ", std::setw(width_pms), pixels_per_ms, " pixels/ms.");
}
/**
* @brief Find the index of the minimum element in a vector.
*
* @tparam T The type of elements in the vector.
* @param vec The vector.
* @return The index of the smallest element in the vector.
*/
template <typename T>
std::size_t min_element_index(const std::vector<T>& vec)
{
return static_cast<std::size_t>(std::distance(vec.begin(), std::min_element(vec.begin(), vec.end())));
}
/**
* @brief Calculate and print the speedup obtained by multithreading.
*
* @param timings A vector of the timings corresponding to different numbers of tasks.
* @param try_tasks A vector containing the numbers of tasks tried.
*/
void print_speedup(const std::vector<double>& timings, const std::vector<std::size_t>& try_tasks)
{
const std::size_t min_el = min_element_index(timings);
const double max_speedup = std::round((timings[0] / timings[min_el]) * 10) / 10;
const std::size_t num_tasks = try_tasks[min_el];
logln("Maximum speedup obtained by multithreading vs. single-threading: ", max_speedup, "x, using ", num_tasks, " tasks.");
}
/**
* @brief Calculate the mean and standard deviation of a set of integers.
*
* @param timings The integers.
* @return A struct containing the mean and standard deviation.
*/
mean_sd analyze(const std::vector<std::chrono::milliseconds::rep>& timings)
{
// First, calculate the mean <X> and the mean of the square <X^2>.
double mean = 0;
double mean_sq = 0;
for (const std::chrono::milliseconds::rep timing : timings)
{
mean += static_cast<double>(timing);
mean_sq += static_cast<double>(timing * timing);
}
mean /= static_cast<double>(timings.size());
mean_sq /= static_cast<double>(timings.size());
// The variance is given by <(X - <X>)^2> = <X^2> - <X>^2. The standard deviation is the square root of the variance.
return {mean, std::sqrt(mean_sq - (mean * mean))};
}
/**
* @brief A class to save the Mandelbrot image in. Note that rows and columns are inverted compared to the usual matrix syntax, so that `image(x, y)` corresponds to the pixel at coordinates (x, y) where x is the horizontal axis (i.e. column number) and y is the vertical axis (i.e. row number). The width is the number of columns and the height is the number of rows.
*/
template <typename T>
class [[nodiscard]] image_matrix
{
public:
image_matrix() = default;
image_matrix(const std::size_t width_, const std::size_t height_) : width(width_), height(height_), pixels(std::make_unique<T[]>(width_ * height_)) {}
[[nodiscard]] T& operator()(std::size_t x, std::size_t y)
{
return pixels[(y * width) + x];
}
[[nodiscard]] T operator()(std::size_t x, std::size_t y) const
{
return pixels[(y * width) + x];
}
[[nodiscard]] T& operator[](std::size_t i)
{
return pixels[i];
}
[[nodiscard]] T operator[](std::size_t i) const
{
return pixels[i];
}
[[nodiscard]] std::size_t get_height() const
{
return height;
}
[[nodiscard]] std::size_t get_width() const
{
return width;
}
private:
std::size_t width = 0;
std::size_t height = 0;
std::unique_ptr<T[]> pixels = nullptr;
}; // class matrix
// The maximum number of iterations to try before deciding whether a point is in the Mandelbrot set.
constexpr std::size_t max_iter = 2000;
/**
* @brief Find the escape time of a point.
*
* @param c The point.
* @return The escape time, that is, the number of iterations before the point escapes the Mandelbrot set, with an additional fractional part to eliminate color banding; or `max_iter` if the point doesn't escape within the maximum number of iterations.
*/
double mandelbrot_escape(const std::complex<double> c)
{
// Define the escape radius. A point c is considered to have "escaped" the Mandelbrot set if, after fewer than `max_iter` iterations of the formula z = z^2 + c starting at z = 0, we get |z| > r. Since the Mandelbrot set is contained within a closed disk of radius 2, the escape radius must be at least 2. However, with that choice we will see the actual disk in the image, because any point outside the disk (but still in the output image) will automatically have an iteration count of 1. For the region plotted by this program by default, an escape radius of 4 is enough, but a higher radius generally produces smoother color gradients.
constexpr double r = 1024;
std::complex<double> z = c;
std::size_t iter = 1;
while (std::norm(z) <= (r * r) && iter < max_iter)
{
z = z * z + c;
++iter;
};
// If the point did not escape within the maximum number of iterations, then it is (most likely) in the Mandelbrot set, and we return the maximum number of iterations as is.
if (iter == max_iter)
return static_cast<double>(max_iter);
// If the point escapes, calculate a continuous value to be used for coloring that points in the image. The iteration count is an integer, which would cause color banding in the final image, as there are large regions with the same iteration count and therefore the same color. We resolve this by adding a fractional part. After the loop ends, z has just escaped the radius r, so we are guaranteed that |r| < |z| < |r^2 + c|. Neglecting c (which we can do if r is large enough), this means log_r(|z|) is in the range [1, 2], and therefore log_2(log_r(|z|)) is in the range [0, 1]. Hence, the quantity log_2(log_r(|z|)) = log_2(log(|z|)/log(r)) = log_2(log(|z|^2)/log(r^2)) provides a fractional part that we can simply add to the integer iteration count to make it continuous and eliminate the banding. We subtract from the iteration count instead of adding to it, because larger values of z have smaller iteration counts.
return static_cast<double>(iter) - std::log2(std::log(std::norm(z)) / std::log(r * r));
}
/**
* @brief A helper struct to store the RGB values of a pixel.
*/
struct [[nodiscard]] color
{
constexpr color() = default;
template <typename T>
constexpr color(const T r_, const T g_, const T b_) : r(static_cast<std::uint8_t>(r_)), g(static_cast<std::uint8_t>(g_)), b(static_cast<std::uint8_t>(b_))
{
}
std::uint8_t r = 0;
std::uint8_t g = 0;
std::uint8_t b = 0;
};
/**
* @brief Interpolate between two colors.
*
* @param first The first color.
* @param second The second color.
* @param t The interpolation point, in the range [0, 1] where 0 corresponds to the first color, 1 corresponds to the second color, and any other value combines the two colors.
* @return The interpolated color.
*/
color interpolate_colors(const color& first, const color& second, const double t)
{
return {first.r + (t * (second.r - first.r)), first.g + (t * (second.g - first.g)), first.b + (t * (second.b - first.b))};
}
/**
* @brief Convert the escape time of a point into a color.
*
* @param iterations The fractional number of iterations before the point escapes the Mandelbrot set.
* @return The color.
*/
color iter_to_color(const double iterations)
{
// Define a nice color palette for the image.
static constexpr std::array<color, 16> palette = {{{66, 30, 15}, {25, 7, 26}, {9, 1, 47}, {4, 4, 73}, {0, 7, 100}, {12, 44, 138}, {24, 82, 177}, {57, 125, 209}, {134, 181, 229}, {211, 236, 248}, {241, 233, 191}, {248, 201, 95}, {255, 170, 0}, {204, 128, 0}, {153, 87, 0}, {106, 52, 3}}};
// Points that are in the set (or at least, suspected to be in the set because they did not diverge after the maximum number of iterations) will be black.
if (iterations == max_iter)
return {0, 0, 0};
// Get the integer and fractional parts of the number of iterations.
double int_part = 0;
const double frac_part = std::modf(iterations, &int_part);
// Choose two adjacent colors from the palette based on the integer part. We cycle through the palette, so the same colors will repeat many times (`max_iter` is much larger than the number of colors).
const color color1 = palette[static_cast<std::size_t>(int_part) % palette.size()];
const color color2 = palette[(static_cast<std::size_t>(int_part) + 1) % palette.size()];
// Use the fractional part to interpolate smoothly between the two colors.
return interpolate_colors(color1, color2, frac_part);
}
/**
* @brief Calculate the colors of a range of pixels in an image, enumerated as a range of indices in a 1-dimensional array containing the flattened matrix in row-major order.
*
* @param image The matrix storing the image.
* @param start The first index to calculate.
* @param end The index after the last index to calculate.
* @param jump How many pixels to jump over each iteration, to allow for splitting the work between different runs of the same test.
* @param offset How many pixels to shift the calculation by.
*/
void calculate_mandelbrot(image_matrix<color>& image, const std::size_t start, const std::size_t end, const std::size_t jump, const std::size_t offset)
{
// Define the ranges of real and imaginary values to consider for the Mandelbrot set. The aspect ratio should be exactly 1:1 (width:height) to prevent stretching, since the benchmark always outputs square images for simplicity.
constexpr double re_min = -2.01;
constexpr double re_max = 0.51;
constexpr double im_min = -1.26;
constexpr double im_max = 1.26;
// Get the width and height of the image.
const std::size_t width = image.get_width();
const std::size_t height = image.get_height();
for (std::size_t i = start + offset; i < end; i += jump)
{
// Convert the pixel index to the corresponding x and y coordinates.
const std::size_t x = i % width;
const std::size_t y = i / width;
// Convert the pixel coordinates, integers (x, y) such that x is in [0, width-1] and y is in [0, height-1], to a complex number c such that Re(c) is in [re_min, re_max] and Im(c) is in [im_min, im_max]}. (Note: We also need to invert the y axis because the y value increases downwards in the image, but the imaginary part increases upwards in the complex plane. However, to avoid doing any extra calculations, we do that later when we save the image.)
const std::complex<double> c = {(static_cast<double>(x) / static_cast<double>(width) * (re_max - re_min)) + re_min, (static_cast<double>(y) / static_cast<double>(height) * (im_max - im_min)) + im_min};
// Calculate the pixel's escape time and convert it to a color.
image[i] = iter_to_color(mandelbrot_escape(c));
}
}
// A macro to unpack a 16-bit integer into 2 bytes.
#define UNPACK_2_BYTES(value) static_cast<std::uint8_t>(value), static_cast<std::uint8_t>((value) >> 8)
// A macro to unpack a 32-bit integer into 4 bytes.
#define UNPACK_4_BYTES(value) static_cast<std::uint8_t>(value), static_cast<std::uint8_t>((value) >> 8), static_cast<std::uint8_t>((value) >> 16), static_cast<std::uint8_t>((value) >> 24)
/**
* @brief Save an image to a BMP file.
*
* @param image The matrix containing the pixels.
* @param filename The output file name.
*/
void save_bmp(const image_matrix<color>& image, const std::string& filename)
{
// Create the file.
std::ofstream file(filename, std::ios::binary);
if (!file.is_open())
{
logln_ansi(ansi_error, "Error: Could not create the file ", filename, '.');
return;
}
log("Saving image to a BMP file: [");
// Calculate the size of the BMP file in bytes.
const std::uint32_t width = static_cast<std::uint32_t>(image.get_width());
const std::uint32_t height = static_cast<std::uint32_t>(image.get_height());
const std::uint32_t total_pixels = width * height;
constexpr std::uint32_t file_header_size = 14;
constexpr std::uint32_t info_header_size = 40;
constexpr std::uint32_t bytes_per_pixel = 3;
constexpr std::uint32_t bits_per_pixel = bytes_per_pixel * 8;
const std::uint32_t file_size = file_header_size + info_header_size + (bytes_per_pixel * total_pixels);
// The file header of the BMP file: 2 bytes for the "BM" signature, 4 bytes for the file size, 4 bytes reserved, 4 bytes for the start offset of the pixel array. Note that all integers are stored in little-endian format (least-significant byte first), hence the bit shifts (from the macro UNPACK_4_BYTES). We specify the values explicitly to avoid issues with padding.
const std::uint8_t bmp_file_header[file_header_size] = {'B', 'M', UNPACK_4_BYTES(file_size), UNPACK_4_BYTES(0), UNPACK_4_BYTES(file_header_size + info_header_size)};
// The information header of the BMP file: 4 bytes for the header size, 4 bytes for the image width, 4 bytes for the image height, 2 bytes for the number of color planes, 2 bytes for the number of bits per pixel, 4 bytes for the compression method (0 = no compression), 4 bytes for the image size (can be 0 if no compression), 4 bytes for the horizontal pixels per meter, 4 bytes for the vertical pixels per meter, 4 bytes for the number of colors (0 = default), 4 bytes for the number of "important colors" (generally ignored).
const std::uint8_t bmp_info_header[info_header_size] = {UNPACK_4_BYTES(info_header_size), UNPACK_4_BYTES(width), UNPACK_4_BYTES(height), UNPACK_2_BYTES(1), UNPACK_2_BYTES(bits_per_pixel), UNPACK_4_BYTES(0), UNPACK_4_BYTES(0), UNPACK_4_BYTES(0), UNPACK_4_BYTES(0), UNPACK_4_BYTES(0), UNPACK_4_BYTES(0)};
// Write the headers.
file.write(reinterpret_cast<const char*>(bmp_file_header), file_header_size);
file.write(reinterpret_cast<const char*>(bmp_info_header), info_header_size);
// Create padding bytes for later use.
const std::uint8_t padding_bytes[3] = {0, 0, 0};
const std::streamsize num_padding_bytes = (4 - ((width * bytes_per_pixel) % 4)) % 4;
// Write the pixels. Note that they are stored "bottom-up", starting in the lower left corner, going from left to right and then row by row. However, we need to invert the y axis anyway, because the y value increases downwards in the image, but the imaginary part increases upwards in the complex plane. Therefore, we just use the normal y values when saving the image.
for (std::size_t y = 0; y < height; ++y)
{
for (std::size_t x = 0; x < width; ++x)
{
const color col = image(x, y);
// BMP format stores the colors in BGR order.
file.write(reinterpret_cast<const char*>(&col.b), 1);
file.write(reinterpret_cast<const char*>(&col.g), 1);
file.write(reinterpret_cast<const char*>(&col.r), 1);
}
if (num_padding_bytes != 0)
{
// BMP format requires that each row is a multiple of 4 bytes long, so we add padding if necessary.
file.write(reinterpret_cast<const char*>(padding_bytes), num_padding_bytes);
}
if (y % (height / 10) == 0)
log('.');
}
file.close();
logln("]\nMandelbrot image saved successfully as ", filename, '.');
}
/**
* @brief A utility class to measure execution time for benchmarking purposes.
*/
class [[nodiscard]] timer
{
public:
/**
* @brief Get the number of milliseconds that have elapsed since the object was constructed or since `start()` was last called, but keep the timer ticking.
*
* @return The number of milliseconds.
*/
[[nodiscard]] std::chrono::milliseconds::rep current_ms() const
{
return (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_time)).count();
}
/**
* @brief Start (or restart) measuring time. Note that the timer starts ticking as soon as the object is created, so this is only necessary if we want to restart the clock later.
*/
void start()
{
start_time = std::chrono::steady_clock::now();
}
/**
* @brief Stop measuring time and store the elapsed time since the object was constructed or since `start()` was last called.
*/
void stop()
{
elapsed_time = std::chrono::steady_clock::now() - start_time;
}
/**
* @brief Get the number of milliseconds stored when `stop()` was last called.
*
* @return The number of milliseconds.
*/
[[nodiscard]] std::chrono::milliseconds::rep ms() const
{
return (std::chrono::duration_cast<std::chrono::milliseconds>(elapsed_time)).count();
}
private:
/**
* @brief The time point when measuring started.
*/
std::chrono::time_point<std::chrono::steady_clock> start_time = std::chrono::steady_clock::now();
/**
* @brief The duration that has elapsed between `start()` and `stop()`.
*/
std::chrono::duration<double> elapsed_time = std::chrono::duration<double>::zero();
}; // class timer
/**
* @brief Map a color to a monochrome Unicode block based on its brightness, using luma coefficients.
*
* @param col The color.
* @return The Unicode block representing the brightness of the color, in UTF-8.
*/
std::string_view brightness_block(const color& col)
{
// Define Unicode blocks from darkest to brightest in UTF-8.
constexpr std::array<std::string_view, 5> blocks = {" ", "\xE2\x96\x91", "\xE2\x96\x92", "\xE2\x96\x93", "\xE2\x96\x88"};
// Compute the perceived brightness using luma coefficients. Each color component is a number in the range 0-255, and the coefficients sum to 1, so the brightness is also in the range 0-255.
const double brightness = (0.2126 * col.r) + (0.7152 * col.g) + (0.0722 * col.b);
// Quantize the brightness into 5 levels. A brightness of 0 maps to level 0, and a brightness of 255 maps to level 4.
const std::size_t level = static_cast<std::size_t>(std::round(brightness * 4.0 / 255.0));
// Return the corresponding block character.
return blocks[level];
}
/**
* @brief Create a plot of an image as characters, using either 24-bit ANSI colors or monochrome blocks of different brightness.
*
* @param image The image to plot.
* @param out_width The plot width in terminal characters. Should be even, since in the monochrome case each pixel spans two characters horizontally.
* @param use_color `true` to generate a colored plot, `false` to generate a monochrome plot.
* @return The plot as a string.
*/
std::string plot_image_chars(const image_matrix<color>& image, const std::size_t out_width, const bool use_color)
{
// Get the source image dimensions.
const std::size_t src_width = image.get_width();
const std::size_t src_height = image.get_height();
// Compute the plot height in terminal characters, keeping in mind that characters have an aspect ratio of about 1:2 (width:height).
const std::size_t out_height = static_cast<std::size_t>(std::llround(0.5 * static_cast<double>(src_height) * static_cast<double>(out_width) / static_cast<double>(src_width)));
// Create a buffer for the plot.
std::string plot;
// For the colored plot we use Unicode lower half blocks to pack two pixels per character. The background color sets the color of the top (empty) half, and the foreground color sets the color of the bottom (filled) half.
if (use_color)
{
// Each character row contains two pixel rows (top and bottom).
const std::size_t out_height_pixels = out_height * 2;
// Create a mapping of output x coordinates to source pixels, such that x_map[0] = 0 and x_map[out_width - 1] = src_width - 1.
std::vector<std::size_t> x_map(out_width);
for (std::size_t x = 0; x < out_width; ++x)
x_map[x] = (x * (src_width - 1)) / (out_width - 1);
// Create a mapping of output pixel y coordinates to source pixels, such that y_map[0] = 0 and y_map[out_height_pixels - 1] = src_height - 1.
std::vector<std::size_t> y_map(out_height_pixels);
for (std::size_t y = 0; y < out_height_pixels; ++y)
y_map[y] = (y * (src_height - 1)) / (out_height_pixels - 1);
// Reserve enough capacity for the entire plot to avoid reallocations. Each row contains ANSI codes of the form `\033[48;2;RRR;GGG;BBBm\033[38;2;RRR;GGG;BBBm` = up to 38 bytes, plus the Unicode lower half block U+2584 in UTF-8 = 3 bytes, for a total of 41 bytes per character of the plot, plus the `\033[0m` reset code at the end and the newline = 5 bytes.
plot.reserve(out_height * ((out_width * 41) + 5));
// Iterate over the rows and columns.
for (std::size_t y = 0; y < out_height; ++y)
{
for (std::size_t x = 0; x < out_width; ++x)
{
// Fetch the sampled source pixel for the top and bottom halves.
const color col_top = image(x_map[x], y_map[2 * y]);
const color col_bottom = image(x_map[x], y_map[(2 * y) + 1]);
// Create the background color ANSI sequence for the top half.
plot.append("\033[48;2;");
plot.append(std::to_string(col_top.r));
plot.push_back(';');
plot.append(std::to_string(col_top.g));
plot.push_back(';');
plot.append(std::to_string(col_top.b));
// Finish the sequence with `m` and create the foreground color ANSI sequence for the bottom half.
plot.append("m\033[38;2;");
plot.append(std::to_string(col_bottom.r));
plot.push_back(';');
plot.append(std::to_string(col_bottom.g));
plot.push_back(';');
plot.append(std::to_string(col_bottom.b));
// Finish the sequence with `m` and append a lower half block (U+2584) in UTF-8, which is the actual character that will be displayed.
plot.append("m\xE2\x96\x84");
}
// Reset the ANSI style at the end of the row and add a newline character.
plot.append("\033[0m\n");
}
}
// For the monochrome plot we use Unicode block characters of different brightness levels. Each pixel is rendered as two identical blocks side-by-side to make the pixels square (so essentially, the opposite of the colored plot).
else
{
// Each pixel spans two terminal characters horizontally.
const std::size_t out_width_pixels = out_width / 2;
// Create a mapping of output x coordinates to source pixels, such that x_map[0] = 0 and x_map[out_width_pixels - 1] = src_width - 1.
std::vector<std::size_t> x_map(out_width_pixels);
for (std::size_t x = 0; x < out_width_pixels; ++x)
x_map[x] = (x * (src_width - 1)) / (out_width_pixels - 1);
// Create a mapping of output y coordinates to source pixels, such that y_map[0] = 0 and y_map[out_height - 1] = src_height - 1.
std::vector<std::size_t> y_map(out_height);
for (std::size_t y = 0; y < out_height; ++y)
y_map[y] = (y * (src_height - 1)) / (out_height - 1);
// Reserve enough capacity for the entire plot to avoid reallocations. The UTF-8 blocks can take up to 3 bytes each, plus a newline after each row.
plot.reserve(out_height * ((out_width * 3) + 1));
// Iterate over the rows and columns.
for (std::size_t y = 0; y < out_height; ++y)
{
for (std::size_t x = 0; x < out_width_pixels; ++x)
{
// Fetch the sampled source pixel and map to a Unicode block based on brightness.
const color col = image(x_map[x], y_map[y]);
const std::string_view block = brightness_block(col);
plot.append(block);
plot.append(block);
}
// Add a newline after each row.
plot.push_back('\n');
}
}
return plot;
}
/**
* @brief Benchmark multithreaded performance by calculating the Mandelbrot set.
*
* @param benchmark Whether to perform the full benchmarks.
* @param plot Whether to perform quick benchmarks by just plotting the image once.
* @param save Whether to save the image as a BMP file.
*/
void check_performance(const bool benchmark, const bool plot, const bool save)
{
print_header("Preparing benchmarks:");
#ifdef BS_THREAD_POOL_NATIVE_EXTENSIONS
// Try to give the process the highest possible priority, so that other processes do not interfere with the benchmarks.
if (!BS::set_os_process_priority(BS::os_process_priority::realtime))
if (!BS::set_os_process_priority(BS::os_process_priority::high))
BS::set_os_process_priority(BS::os_process_priority::above_normal);
const std::string process_priority = os_process_priority_name(BS::get_os_process_priority());
logln("Process priority set to: ", process_priority, ".");
if (process_priority != "realtime")
logln_ansi(ansi_info, "Note: Please run as admin/root to enable a higher process priority.");
try_os_thread_priority();
const std::string thread_priority = os_thread_priority_name(BS::this_thread::get_os_thread_priority());
logln("Thread priority set to: ", thread_priority, ".");
if (thread_priority != "realtime")
logln_ansi(ansi_info, "Note: Please run as admin/root to enable a higher thread priority.");
// Initialize a thread pool with the default number of threads, and ensure that the threads have the highest possible priority, so that other processes do not interfere with the benchmarks.
BS::thread_pool pool(try_os_thread_priority);
#else
// If native extensions are disabled, just initialize a thread pool with the default number of threads.
BS::thread_pool pool;
#endif
// Store the number of available hardware threads for easy access.
const std::size_t thread_count = pool.get_thread_count();
logln("Using ", thread_count, " threads.");
// Set the formatting of floating point numbers.
log(std::fixed, std::setprecision(1));
// Initialize a timer object to measure execution time.
timer tmr;
// The target execution time, in milliseconds, of the multithreaded test with the number of blocks equal to the number of threads. The total time spent on that test will be approximately equal to `repeat * target_ms`.
constexpr std::chrono::milliseconds::rep target_ms = 50;
// Find the Mandelbrot image size that will roughly achieve the target execution time.
logln("Determining the Mandelbrot image size needed to achieve an approximate mean execution time of ", target_ms, " ms with ", thread_count, " tasks...");
std::size_t image_size = thread_count;
image_matrix<color> image;
std::size_t jump = 1;
std::size_t offset = 0;
// Define the loop function.
const auto loop = [&image, &jump, &offset](const std::size_t start, const std::size_t end)
{
calculate_mandelbrot(image, start, end, jump, offset);
};
// Increase the image size gradually until the target execution time is reached.
do
{
image_size *= 2;
image = image_matrix<color>(image_size, image_size);
tmr.start();
pool.detach_blocks(0, image_size * image_size, loop);
pool.wait();
tmr.stop();
} while (tmr.ms() < target_ms);
// Scale the image size to fit the target execution time more precisely, keeping in mind that the time complexity is O(image_size^2).
image_size = static_cast<std::size_t>(std::llround(static_cast<double>(image_size) * std::sqrt(static_cast<double>(target_ms) / static_cast<double>(tmr.ms()))));
logln("Result: ", image_size, 'x', image_size, " pixels.");
if (benchmark)
{
print_header("Performing full benchmarks:");
// Define vectors to store statistics.
std::vector<double> different_n_timings;
std::vector<std::chrono::milliseconds::rep> same_n_timings;
// The number of times to repeat each run of the test in order to collect reliable statistics.
constexpr std::size_t num_repeats = 30;
// Since we are repeating the same test multiple times, we might as well use different parts of the complex plane in each repetition. However, we have to spread the calculations evenly to avoid biasing the results, as some regions have much higher escape times than others. So we calculate the whole image, but at an offset from 0 to `num_repeats`.
jump = num_repeats;
const std::size_t benchmark_image_size = static_cast<std::size_t>(std::floor(static_cast<double>(image_size) * std::sqrt(num_repeats)));
logln("Generating a ", benchmark_image_size, 'x', benchmark_image_size, " plot of the Mandelbrot set...");
logln("Each test will be repeated ", num_repeats, " times to collect reliable statistics.");
// Perform the test.
std::vector<std::size_t> try_tasks;
std::size_t num_tasks = 0;
double last_timing = std::numeric_limits<double>::max();
constexpr int width_tasks = 4;
while (true)
{
image = image_matrix<color>(benchmark_image_size, benchmark_image_size);
try_tasks.push_back(num_tasks);
if (num_tasks == 0)
log(std::setw(width_tasks), 1, " task: ");
else
log(std::setw(width_tasks), num_tasks, " tasks: ");
log('[', BS::synced_stream::flush);
for (std::size_t i = 0; i < num_repeats; ++i)
{
// Measure execution time for this test.
tmr.start();
if (num_tasks > 0)
{
pool.detach_blocks(0, benchmark_image_size * benchmark_image_size, loop, num_tasks);
pool.wait();
}
else
{
loop(0, benchmark_image_size * benchmark_image_size);
}
tmr.stop();
// Save the measurement for later analysis.
same_n_timings.push_back(tmr.ms());
// Print a dot to inform the user that we've made progress.
log('.', BS::synced_stream::flush);
// Increase the offset so we calculate a different part of the image in each repetition of the test.
offset = (offset + 1) % num_repeats;
}
logln(']', (num_tasks == 0) ? " (single-threaded)" : "");
// Analyze, print, and save the mean and standard deviation of all the tests with the same number of tasks.
const mean_sd stats = analyze(same_n_timings);
const std::chrono::milliseconds::rep total_time = std::reduce(same_n_timings.begin(), same_n_timings.end());
const double pixels_per_ms = static_cast<double>(benchmark_image_size * benchmark_image_size) / static_cast<double>(total_time);
same_n_timings.clear();
print_timing(stats, pixels_per_ms);
different_n_timings.push_back(stats.mean);
if (num_tasks == 0)
{
num_tasks = std::max<std::size_t>(thread_count / 4, 2);
}
else
{
if ((num_tasks > thread_count) && (stats.mean > last_timing))
break;
last_timing = stats.mean;
num_tasks *= 2;
}
}
print_speedup(different_n_timings, try_tasks);
}
if (plot)
{
print_header("Performing quick benchmarks:");
// Just plot whatever we can in 5 seconds. Feel free to increase this to get higher resolution images.
constexpr std::chrono::milliseconds::rep total_ms = 5000;
const std::size_t plot_image_size = static_cast<std::size_t>(std::floor(static_cast<double>(image_size) * std::sqrt(static_cast<double>(total_ms) / static_cast<double>(target_ms))));
image = image_matrix<color>(plot_image_size, plot_image_size);
log("Generating a ", plot_image_size, 'x', plot_image_size, " plot of the Mandelbrot set with ", thread_count, " tasks: [", BS::synced_stream::flush);
pool.detach_blocks(0, plot_image_size * plot_image_size,
[&image](const std::size_t start, const std::size_t end)
{
calculate_mandelbrot(image, start, end, 1, 0);
log('.', BS::synced_stream::flush);
});
pool.wait();
tmr.stop();
logln("]\nDone in ", tmr.ms(), " ms (", static_cast<double>(plot_image_size * plot_image_size) / static_cast<double>(tmr.ms()), " pixels/ms).");
}
logln();
// Set the plot width in terminal characters.
constexpr std::size_t plot_width = 120;
// Generate a colored or monochrome plot as needed.
std::string plot_color;
std::string plot_mono;
if (use_stdout && !no_color)
plot_color = plot_image_chars(image, plot_width, true);
if (use_log || (use_stdout && no_color))
plot_mono = plot_image_chars(image, plot_width, false);
// Write the plots to stdout and/or the log file.
if (use_stdout)
sync_cout.print(no_color ? plot_mono : plot_color);
if (use_log)
sync_log.print(plot_mono);
// Save the plot to a BMP file if requested.
if (save)
save_bmp(image, "BS_thread_pool_benchmark_mandelbrot.bmp");
print_header("Thread pool performance test completed successfully!", '+', ansi_success);
}
// ==================================
// The main function and related code
// ==================================
/**
* @brief Show basic information about the program.
*/
void show_intro()
{
logln_ansi(ansi_title, R"(
██████ ███████ ████████ ██ ██ ██████ ███████ █████ ██████ ██████ ██████ ██████ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██████ ███████ ██ ███████ ██████ █████ ███████ ██ ██ ██████ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██████ ███████ ██ ██ ██ ██ ██ ███████ ██ ██ ██████ ███████ ██ ██████ ██████ ███████
)");
logln_ansi(ansi_title_italic, "BS::thread_pool:", " a fast, lightweight, modern, and easy-to-use C++17/C++20/C++23 thread pool library");
logln_ansi(ansi_title_italic, "Copyright (c) 2021-2026 Barak Shoshany (baraksh@gmail.com) (https://baraksh.com/)");
logln_ansi(ansi_title_italic, "GitHub: https://github.com/bshoshany/thread-pool");
logln();
print_key_values("Thread pool library version is: ", 'v', BS::thread_pool_version);
print_key_values("Thread pool library imported using: ", BS::thread_pool_module ? "import BS.thread_pool (" : "#include \"BS_thread_pool.hpp\" (no ", "C++20 modules)");
logln();
logln_ansi(ansi_title_underline, "C++ Standard Library imported using:");
print_key_values("* Thread pool library: ", BS::thread_pool_import_std ? "import std (" : "#include <...> (no ", "C++23 std module)");
print_key_values("* Test program: ", using_import_std ? "import std (" : "#include <...> (no ", "C++23 std module)");
logln();
print_key_values("Detected OS: ", detect_os());
print_key_values("Detected compiler: ", detect_compiler());
print_key_values("Detected standard library: ", detect_lib());
print_key_values("Detected C++ standard: ", detect_cpp_standard(), " (__cplusplus = ", __cplusplus, ")");
logln();
logln_ansi(ansi_title_underline, "Detected features:");
print_features();
print_key_values("Native extensions are: ", BS::thread_pool_native_extensions ? "Enabled" : "Disabled");
print_key_values("Hardware concurrency is: ", std::thread::hardware_concurrency());
logln();
log_ansi(ansi_title_underline, "Important:");
logln_ansi(ansi_title, " Please do not run any other applications, especially multithreaded applications, in parallel with this test!");
}
/**
* @brief Get a string representing the current time.
*
* @return The string.
*/
std::string get_time()
{
#ifdef __cpp_lib_format
// Things are much easier with C++20 `std::format`.
return std::format("{:%Y-%m-%d_%H.%M.%S}", std::chrono::time_point_cast<std::chrono::seconds>(std::chrono::system_clock::now()));
#else
std::string time_string = "YYYY-MM-DD_HH.MM.SS";
std::tm local_tm = {};
const std::time_t epoch = std::time(nullptr);
#if defined(_MSC_VER) && !defined(__cpp_lib_modules)
// If MSVC is detected, use `localtime_s()` to avoid warning C4996. (This doesn't work if we used `import std`, so we check that to be on the safe side, although in that case `std::format` should be available anyway).
if (localtime_s(&local_tm, &epoch) != 0)
time_string = "";
#elif defined(__linux__) || defined(__APPLE__)
// On Linux or macOS, use `localtime_r()` to avoid clang-tidy warning `concurrency-mt-unsafe`.
if (localtime_r(&epoch, &local_tm) == nullptr)
time_string = "";
#else
local_tm = *std::localtime(&epoch); // NOLINT(concurrency-mt-unsafe)
#endif
if (!time_string.empty())
{
const std::size_t bytes = std::strftime(time_string.data(), time_string.length() + 1, "%Y-%m-%d_%H.%M.%S", &local_tm);
if (bytes != time_string.length())
time_string = "";
}
return time_string;
#endif
}
/**
* @brief A class to parse command line arguments. All arguments are simple on/off flags.
*/
class [[nodiscard]] arg_parser
{
public:
/**
* @brief Convert the command line arguments passed to the `main()` function into an `std::vector`.
*
* @param argc The number of arguments.
* @param argv An array containing the arguments.
*/
arg_parser(int argc, char* argv[]) : args(argv + 1, argv + argc), executable(argv[0]) {};
/**
* @brief Check if a specific command line argument has been passed to the program. If no arguments were passed, use the default value instead.
*
* @param arg The argument to check for.
* @return `true` if the argument exists, `false` otherwise.
*/
[[nodiscard]] bool operator[](const std::string_view arg)
{
if (size() > 0)
return (args.count(arg) == 1);
return allowed[arg].def;
}
/**
* @brief Add an argument to the list of allowed arguments.
*
* @param arg The argument.
* @param desc The description of the argument.
* @param def The default value of the argument.
*/
void add_argument(const std::string_view arg, const std::string_view desc, const bool def)
{
allowed[arg] = {desc, def};
}
/**
* @brief Get the name of the executable.
*
* @return The name of the executable.
*/
std::string_view get_executable()
{
return executable;
}
void show_help() const
{
int width = 1;
for (const auto& [arg, opt] : allowed)
width = std::max(width, static_cast<int>(arg.size()));
logln("\nAvailable options (all are on/off and default to off):");
for (const auto& [arg, opt] : allowed)
logln(" ", std::left, std::setw(width), arg, " ", opt.desc);
log("If no options are entered, the default is:\n ");
for (const auto& [arg, opt] : allowed)
{
if (opt.def)
log(arg, " ");
}
logln();
}
/**
* @brief Get the number of command line arguments.
*
* @return The number of arguments.
*/
[[nodiscard]] std::size_t size() const
{
return args.size();
}
/**
* @brief Verify that the command line arguments belong to the list of allowed arguments.
*
* @return `true` if all arguments are allowed, `false` otherwise.
*/
[[nodiscard]] bool verify() const
{
return std::all_of(args.begin(), args.end(),
[this](const std::string_view arg)
{
return allowed.count(arg) == 1;
});
}
private:
struct arg_spec
{
std::string_view desc;
bool def = false;
};
/**
* @brief A set containing string views of the command line arguments.
*/
std::set<std::string_view> args;
/**
* @brief A map containing the allowed arguments and their descriptions.
*/
std::map<std::string_view, arg_spec> allowed;
/**
* @brief A string view containing the name of the executable.
*/
std::string_view executable;
}; // class arg_parser
} // anonymous namespace
int main(int argc, char* argv[]) // NOLINT(bugprone-exception-escape)
{
#ifdef __cpp_exceptions
try
{
#endif
// Disable ANSI colors if the environment variable `NO_COLOR` is set.
no_color = (std::getenv("NO_COLOR") != nullptr); // NOLINT(concurrency-mt-unsafe)
// If the file default_args.txt exists in either this folder or the parent folder, read the default arguments from it (space separated in a single line). Otherwise, use the built-in defaults. This is useful when debugging.
std::map<std::string, bool> defaults;
std::ifstream default_args_file("default_args.txt");
if (!default_args_file.is_open())
default_args_file.open("../default_args.txt");
if (default_args_file.is_open())
{
std::string line;
std::getline(default_args_file, line);
std::istringstream iss(line);
std::string arg;
while (iss >> arg)
defaults[arg] = true;
default_args_file.close();
}
else
{
defaults = {{"help", false}, {"stdout", true}, {"log", true}, {"tests", true}, {"deadlock", false}, {"benchmarks", true}, {"plot", false}, {"save", false}};
}
// Parse the command line arguments.
arg_parser args(argc, argv);
args.add_argument("help", "Show this help message and exit.", defaults["help"]);
args.add_argument("stdout", "Print to the standard output.", defaults["stdout"]);
args.add_argument("log", "Print to a log file.", defaults["log"]);
args.add_argument("tests", "Perform standard tests.", defaults["tests"]);
args.add_argument("deadlock", "Perform long deadlock tests.", defaults["deadlock"]);
args.add_argument("benchmarks", "Perform full Mandelbrot plot benchmarks.", defaults["benchmarks"]);
args.add_argument("plot", "Perform quick Mandelbrot plot benchmarks.", defaults["plot"]);
args.add_argument("save", "Save the Mandelbrot plot to a file.", defaults["save"]);
if (args.size() > 0)
{
if (args["help"] || !args.verify())
{
show_intro();
args.show_help();
return 0;
}
if (!args["stdout"] && !args["log"])
{
show_intro();
args.show_help();
logln_ansi(ansi_error, "\nERROR: No output stream specified! Please enter one or more of: log, stdout. Aborting.");
return 0;
}
if (!args["benchmarks"] && !args["deadlock"] && !args["plot"] && !args["tests"])
{
show_intro();
args.show_help();
logln_ansi(ansi_error, "\nERROR: No tests or benchmarks requested! Please enter one or more of: benchmarks, deadlock, plot, tests. Aborting.");
return 0;
}
}
// A stream object used to access the log file.
std::ofstream log_file;
sync_log.remove_stream(std::cout);
if (args["log"])
{
// Extract the name of the executable file, or use a default value if it is not available.
const std::string_view executable = args.get_executable();
const std::size_t last_slash = executable.find_last_of("/\\") + 1;
std::string exe_file(executable.substr(last_slash, executable.find('.', last_slash) - last_slash));
if (exe_file.empty())
exe_file = "BS_thread_pool_test";
// Create a log file using the name of the executable, followed by the current date and time.
const std::string log_filename = exe_file + "-" + get_time() + ".log";
log_file.open(log_filename);
if (log_file.is_open())
{
logln_ansi(ansi_info, "Generating log file: ", log_filename);
sync_log.add_stream(log_file);
}
else
{
logln_ansi(ansi_error, "ERROR: Could not create a log file.");
return 1;
}
}
use_stdout = args["stdout"];
use_log = args["log"];
show_intro();
if (args["tests"])
{
print_header("Checking the constructor:");
check_constructor();
print_header("Checking reset():");
check_reset();
print_header("Checking detach_task() and submit_task():");
check_task("detach_task()");
check_task("submit_task()");
print_header("Checking submission of member functions as tasks:");
check_member_function();
check_member_function_within_object();
print_header("Checking submission of different callable types:");
check_callables();
print_header("Checking wait(), wait_for(), and wait_until():");
check_wait();
check_wait_blocks();
check_wait_for();
check_wait_until();
check_wait_multiple_deadlock();
#ifdef __cpp_exceptions
check_wait_self_deadlock();
print_header("Checking exception handling:");
check_exceptions_submit();
check_exceptions_multi_future();
#else
logln_ansi(ansi_info, "NOTE: Exceptions are disabled, skipping wait deadlock check and exception handling tests.");
#endif
print_header("Checking detach_loop() and submit_loop():");
check_loop();
print_header("Checking detach_blocks() and submit_blocks():");
check_blocks();
print_header("Checking detach_sequence() and submit_sequence():");
check_sequence();
print_header("Checking task monitoring:");
check_task_monitoring();
print_header("Checking pausing:");
check_pausing();
print_header("Checking purge():");
check_purge();
print_header("Checking parallelized vector operations:");
check_vectors();
print_header("Checking task priority:");
check_priority();
print_header("Checking thread initialization/cleanup functions and BS::this_thread:");
check_init();
check_cleanup();
check_get_pool();
print_header("Checking that parallelized tasks do not get copied:");
check_copy_all();
print_header("Checking that shared pointers are correctly shared:");
check_shared_ptr_all();
print_header("Checking that tasks are destructed immediately after running:");
check_task_destruct();
print_header("Checking BS::common_index_type:");
check_common_index_type();
#ifdef BS_THREAD_POOL_NATIVE_EXTENSIONS
print_header("Checking native extensions:");
#ifndef _WIN32
if ((args["benchmarks"] || args["plot"]) && !BS::set_os_process_priority(BS::os_process_priority::realtime))
{
logln_ansi(ansi_info, "NOTE: Skipping process/thread priority checks since the test is running on Linux/macOS without root privileges and benchmarks are enabled. On Linux/macOS, if priorities are decreased, they cannot be increased back to normal without root privileges, so the process will be stuck on the lowest priority, and the benchmarks will be unreliable.\n");
}
else
#endif
{
// Note: We have to check thread priorities first, because the check for process priorities lowers the priority of the process to the lowest level, and on Linux, if not running as root, we can only lower the priority, not raise it, so the process gets stuck on the lowest priority. Since the thread priorities cannot be set to higher than the process priorities, this means the thread priorities will also be stuck on the lowest priority, and the test will fail.
check_os_thread_priorities();
logln();
check_os_process_priorities();
logln();
}
check_os_thread_names();
logln();
#if defined(_WIN32) || defined(__linux__)
check_os_thread_affinity();
logln();
check_os_process_affinity();
#else
logln_ansi(ansi_info, "NOTE: macOS does not support affinity, skipping the corresponding test.");
#endif
#else
logln_ansi(ansi_info, "NOTE: Native extensions disabled, skipping the corresponding test.");
#endif
}
if (args["deadlock"])
{
print_header("Checking for deadlocks:");
logln("Checking for destruction deadlocks...");
check_deadlock(
[]
{
BS::thread_pool temp_pool;
temp_pool.detach_task([] {});
});
logln("Checking for reset deadlocks...");
BS::thread_pool temp_pool;
check_deadlock(
[&temp_pool]
{
temp_pool.reset();
});
}
if (test_results::tests_failed > 0)
{
print_header("FAILURE: Passed " + std::to_string(test_results::tests_succeeded) + " checks, but failed " + std::to_string(test_results::tests_failed) + "!", '+', ansi_error);
logln_ansi(ansi_error, "\nPlease submit a bug report at https://github.com/bshoshany/thread-pool/issues including the exact specifications of your system (OS, CPU, compiler, etc.) and the generated log file.");
log_file.close();
return static_cast<int>(test_results::tests_failed);
}
if (test_results::tests_succeeded > 0)
print_header("SUCCESS: Passed all " + std::to_string(test_results::tests_succeeded) + " checks!", '+', ansi_success);
if (args["benchmarks"] || args["plot"])
check_performance(args["benchmarks"], args["plot"], args["save"]);
log_file.close();
return 0;
#ifdef __cpp_exceptions
}
catch (const std::exception& e)
{
logln_ansi(ansi_error, "ERROR: Tests failed due to exception: ", e.what());
return 1;
}
#endif
}
|