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
|
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/task/single_thread_task_executor.h"
#include <stddef.h>
#include <stdint.h>
#include <string>
#include <vector>
#include "base/compiler_specific.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop/message_pump_for_io.h"
#include "base/message_loop/message_pump_type.h"
#include "base/pending_task.h"
#include "base/posix/eintr_wrapper.h"
#include "base/run_loop.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/current_thread.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/task_observer.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "base/test/bind.h"
#include "base/test/gtest_util.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/test_simple_task_runner.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
#include "base/threading/sequence_local_storage_slot.h"
#include "base/threading/thread.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/android/java_handler_thread.h"
#include "base/android/jni_android.h"
#include "base/test/android/java_handler_thread_helpers.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "base/message_loop/message_pump_win.h"
#include "base/process/memory.h"
#include "base/win/current_module.h"
#include "base/win/message_window.h"
#include "base/win/scoped_handle.h"
#include <windows.h>
#endif
using ::testing::IsNull;
using ::testing::NotNull;
namespace base {
// TODO(darin): Platform-specific MessageLoop tests should be grouped together
// to avoid chopping this file up with so many #ifdefs.
namespace {
class Foo : public RefCounted<Foo> {
public:
Foo() : test_count_(0) {}
Foo(const Foo&) = delete;
Foo& operator=(const Foo&) = delete;
void Test0() { ++test_count_; }
void Test1ConstRef(const std::string& a) {
++test_count_;
result_.append(a);
}
void Test1Ptr(std::string* a) {
++test_count_;
result_.append(*a);
}
void Test1Int(int a) { test_count_ += a; }
void Test2Ptr(std::string* a, std::string* b) {
++test_count_;
result_.append(*a);
result_.append(*b);
}
void Test2Mixed(const std::string& a, std::string* b) {
++test_count_;
result_.append(a);
result_.append(*b);
}
int test_count() const { return test_count_; }
const std::string& result() const { return result_; }
private:
friend class RefCounted<Foo>;
~Foo() = default;
int test_count_;
std::string result_;
};
// This function runs slowly to simulate a large amount of work being done.
static void SlowFunc(TimeDelta pause, int* quit_counter) {
PlatformThread::Sleep(pause);
if (--(*quit_counter) == 0)
RunLoop::QuitCurrentWhenIdleDeprecated();
}
// This function records the time when Run was called in a Time object, which is
// useful for building a variety of SingleThreadTaskExecutor tests.
static void RecordRunTimeFunc(TimeTicks* run_time, int* quit_counter) {
*run_time = TimeTicks::Now();
// Cause our Run function to take some time to execute. As a result we can
// count on subsequent RecordRunTimeFunc()s running at a future time,
// without worry about the resolution of our system clock being an issue.
SlowFunc(Milliseconds(10), quit_counter);
}
enum TaskType {
MESSAGEBOX,
ENDDIALOG,
RECURSIVE,
TIMEDMESSAGELOOP,
QUITMESSAGELOOP,
ORDERED,
PUMPS,
SLEEP,
RUNS,
};
// Saves the order in which the tasks executed.
struct TaskItem {
TaskItem(TaskType t, int c, bool s) : type(t), cookie(c), start(s) {}
TaskType type;
int cookie;
bool start;
bool operator==(const TaskItem& other) const {
return type == other.type && cookie == other.cookie && start == other.start;
}
};
std::ostream& operator<<(std::ostream& os, TaskType type) {
switch (type) {
case MESSAGEBOX:
os << "MESSAGEBOX";
break;
case ENDDIALOG:
os << "ENDDIALOG";
break;
case RECURSIVE:
os << "RECURSIVE";
break;
case TIMEDMESSAGELOOP:
os << "TIMEDMESSAGELOOP";
break;
case QUITMESSAGELOOP:
os << "QUITMESSAGELOOP";
break;
case ORDERED:
os << "ORDERED";
break;
case PUMPS:
os << "PUMPS";
break;
case SLEEP:
os << "SLEEP";
break;
default:
NOTREACHED();
os << "Unknown TaskType";
break;
}
return os;
}
std::ostream& operator<<(std::ostream& os, const TaskItem& item) {
if (item.start)
return os << item.type << " " << item.cookie << " starts";
return os << item.type << " " << item.cookie << " ends";
}
class TaskList {
public:
void RecordStart(TaskType type, int cookie) {
TaskItem item(type, cookie, true);
DVLOG(1) << item;
task_list_.push_back(item);
}
void RecordEnd(TaskType type, int cookie) {
TaskItem item(type, cookie, false);
DVLOG(1) << item;
task_list_.push_back(item);
}
size_t Size() { return task_list_.size(); }
TaskItem Get(int n) { return task_list_[n]; }
private:
std::vector<TaskItem> task_list_;
};
class DummyTaskObserver : public TaskObserver {
public:
explicit DummyTaskObserver(int num_tasks)
: num_tasks_started_(0), num_tasks_processed_(0), num_tasks_(num_tasks) {}
DummyTaskObserver(int num_tasks, int num_tasks_started)
: num_tasks_started_(num_tasks_started),
num_tasks_processed_(0),
num_tasks_(num_tasks) {}
DummyTaskObserver(const DummyTaskObserver&) = delete;
DummyTaskObserver& operator=(const DummyTaskObserver&) = delete;
~DummyTaskObserver() override = default;
void WillProcessTask(const PendingTask& pending_task,
bool /* was_blocked_or_low_priority */) override {
num_tasks_started_++;
EXPECT_LE(num_tasks_started_, num_tasks_);
EXPECT_EQ(num_tasks_started_, num_tasks_processed_ + 1);
}
void DidProcessTask(const PendingTask& pending_task) override {
num_tasks_processed_++;
EXPECT_LE(num_tasks_started_, num_tasks_);
EXPECT_EQ(num_tasks_started_, num_tasks_processed_);
}
int num_tasks_started() const { return num_tasks_started_; }
int num_tasks_processed() const { return num_tasks_processed_; }
private:
int num_tasks_started_;
int num_tasks_processed_;
const int num_tasks_;
};
// A method which reposts itself |depth| times.
void RecursiveFunc(TaskList* order, int cookie, int depth) {
order->RecordStart(RECURSIVE, cookie);
if (depth > 0) {
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&RecursiveFunc, order, cookie, depth - 1));
}
order->RecordEnd(RECURSIVE, cookie);
}
void QuitFunc(TaskList* order, int cookie) {
order->RecordStart(QUITMESSAGELOOP, cookie);
RunLoop::QuitCurrentWhenIdleDeprecated();
order->RecordEnd(QUITMESSAGELOOP, cookie);
}
#if BUILDFLAG(IS_WIN)
void SubPumpFunc(OnceClosure on_done) {
CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop
allow_nestable_tasks;
MSG msg;
while (::GetMessage(&msg, NULL, 0, 0)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
std::move(on_done).Run();
}
const wchar_t kMessageBoxTitle[] = L"SingleThreadTaskExecutor Unit Test";
// SingleThreadTaskExecutor implicitly start a "modal message loop". Modal
// dialog boxes, common controls (like OpenFile) and StartDoc printing function
// can cause implicit message loops.
void MessageBoxFunc(TaskList* order, int cookie, bool is_reentrant) {
order->RecordStart(MESSAGEBOX, cookie);
absl::optional<CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop>
maybe_allow_nesting;
if (is_reentrant)
maybe_allow_nesting.emplace();
::MessageBox(NULL, L"Please wait...", kMessageBoxTitle, MB_OK);
order->RecordEnd(MESSAGEBOX, cookie);
}
// Will end the MessageBox.
void EndDialogFunc(TaskList* order, int cookie) {
order->RecordStart(ENDDIALOG, cookie);
HWND window = GetActiveWindow();
if (window != NULL) {
EXPECT_NE(::EndDialog(window, IDCONTINUE), 0);
// Cheap way to signal that the window wasn't found if RunEnd() isn't
// called.
order->RecordEnd(ENDDIALOG, cookie);
}
}
// A method which posts a RecursiveFunc that will want to run while
// ::MessageBox() is active.
void RecursiveFuncWin(scoped_refptr<SingleThreadTaskRunner> task_runner,
HANDLE event,
bool expect_window,
TaskList* order,
bool message_box_is_reentrant) {
task_runner->PostTask(FROM_HERE, BindOnce(&RecursiveFunc, order, 1, 2));
task_runner->PostTask(
FROM_HERE, BindOnce(&MessageBoxFunc, order, 2, message_box_is_reentrant));
task_runner->PostTask(FROM_HERE, BindOnce(&RecursiveFunc, order, 3, 2));
// The trick here is that for nested task processing, this task will be
// ran _inside_ the MessageBox message loop, dismissing the MessageBox
// without a chance.
// For non-nested task processing, this will be executed _after_ the
// MessageBox will have been dismissed by the code below, where
// expect_window_ is true.
task_runner->PostTask(FROM_HERE, BindOnce(&EndDialogFunc, order, 4));
task_runner->PostTask(FROM_HERE, BindOnce(&QuitFunc, order, 5));
// Enforce that every tasks are sent before starting to run the main thread
// message loop.
ASSERT_TRUE(SetEvent(event));
// Poll for the MessageBox. Don't do this at home! At the speed we do it,
// you will never realize one MessageBox was shown.
for (; expect_window;) {
HWND window = ::FindWindowW(L"#32770", kMessageBoxTitle);
if (window) {
// Dismiss it.
for (;;) {
HWND button = ::FindWindowExW(window, NULL, L"Button", NULL);
if (button != NULL) {
EXPECT_EQ(0, ::SendMessage(button, WM_LBUTTONDOWN, 0, 0));
EXPECT_EQ(0, ::SendMessage(button, WM_LBUTTONUP, 0, 0));
break;
}
}
break;
}
}
}
#endif // BUILDFLAG(IS_WIN)
void Post128KTasksThenQuit(SingleThreadTaskRunner* executor_task_runner,
TimeTicks begin_ticks,
TimeTicks last_post_ticks,
TimeDelta slowest_delay,
OnceClosure on_done,
int num_posts_done = 0) {
const int kNumTimes = 128000;
// Tasks should be running on a decent heart beat. Some platforms/bots however
// have a hard time posting+running *all* tasks before test timeout, add
// detailed logging for diagnosis where this flakes.
const auto now = TimeTicks::Now();
const auto scheduling_delay = now - last_post_ticks;
if (scheduling_delay > slowest_delay)
slowest_delay = scheduling_delay;
if (num_posts_done == kNumTimes) {
std::move(on_done).Run();
return;
} else if (now - begin_ticks >= TestTimeouts::action_max_timeout()) {
ADD_FAILURE() << "Couldn't run all tasks."
<< "\nNumber of tasks remaining: "
<< kNumTimes - num_posts_done
<< "\nSlowest scheduling delay: " << slowest_delay
<< "\nAverage per task: "
<< (now - begin_ticks) / num_posts_done;
std::move(on_done).Run();
return;
}
executor_task_runner->PostTask(
FROM_HERE,
BindOnce(&Post128KTasksThenQuit, Unretained(executor_task_runner),
begin_ticks, now, slowest_delay, std::move(on_done),
num_posts_done + 1));
}
#if BUILDFLAG(IS_WIN)
class TestIOHandler : public MessagePumpForIO::IOHandler {
public:
TestIOHandler(const wchar_t* name, HANDLE signal);
void OnIOCompleted(MessagePumpForIO::IOContext* context,
DWORD bytes_transfered,
DWORD error) override;
void Init();
OVERLAPPED* context() { return &context_.overlapped; }
DWORD size() { return sizeof(buffer_); }
private:
char buffer_[48];
MessagePumpForIO::IOContext context_;
HANDLE signal_;
win::ScopedHandle file_;
};
TestIOHandler::TestIOHandler(const wchar_t* name, HANDLE signal)
: MessagePumpForIO::IOHandler(FROM_HERE), signal_(signal) {
memset(buffer_, 0, sizeof(buffer_));
file_.Set(CreateFile(name, GENERIC_READ, 0, NULL, OPEN_EXISTING,
FILE_FLAG_OVERLAPPED, NULL));
EXPECT_TRUE(file_.is_valid());
}
void TestIOHandler::Init() {
CurrentIOThread::Get()->RegisterIOHandler(file_.get(), this);
DWORD read;
EXPECT_FALSE(ReadFile(file_.get(), buffer_, size(), &read, context()));
EXPECT_EQ(static_cast<DWORD>(ERROR_IO_PENDING), GetLastError());
}
void TestIOHandler::OnIOCompleted(MessagePumpForIO::IOContext* context,
DWORD bytes_transfered,
DWORD error) {
ASSERT_TRUE(context == &context_);
ASSERT_TRUE(SetEvent(signal_));
}
void RunTest_IOHandler() {
win::ScopedHandle callback_called(CreateEvent(NULL, TRUE, FALSE, NULL));
ASSERT_TRUE(callback_called.is_valid());
const wchar_t* kPipeName = L"\\\\.\\pipe\\iohandler_pipe";
win::ScopedHandle server(
CreateNamedPipe(kPipeName, PIPE_ACCESS_OUTBOUND, 0, 1, 0, 0, 0, NULL));
ASSERT_TRUE(server.is_valid());
Thread thread("IOHandler test");
Thread::Options options;
options.message_pump_type = MessagePumpType::IO;
ASSERT_TRUE(thread.StartWithOptions(std::move(options)));
TestIOHandler handler(kPipeName, callback_called.get());
thread.task_runner()->PostTask(
FROM_HERE, BindOnce(&TestIOHandler::Init, Unretained(&handler)));
// Make sure the thread runs and sleeps for lack of work.
PlatformThread::Sleep(Milliseconds(100));
const char buffer[] = "Hello there!";
DWORD written;
EXPECT_TRUE(WriteFile(server.get(), buffer, sizeof(buffer), &written, NULL));
DWORD result = WaitForSingleObject(callback_called.get(), 1000);
EXPECT_EQ(WAIT_OBJECT_0, result);
thread.Stop();
}
#endif // BUILDFLAG(IS_WIN)
} // namespace
//-----------------------------------------------------------------------------
// Each test is run against each type of SingleThreadTaskExecutor. That way we
// are sure that SingleThreadTaskExecutor works properly in all configurations.
// Of course, in some cases, a unit test may only be for a particular type of
// loop.
class SingleThreadTaskExecutorTypedTest
: public ::testing::TestWithParam<MessagePumpType> {
public:
SingleThreadTaskExecutorTypedTest() = default;
SingleThreadTaskExecutorTypedTest(const SingleThreadTaskExecutorTypedTest&) =
delete;
SingleThreadTaskExecutorTypedTest& operator=(
const SingleThreadTaskExecutorTypedTest&) = delete;
~SingleThreadTaskExecutorTypedTest() = default;
static std::string ParamInfoToString(
::testing::TestParamInfo<MessagePumpType> param_info) {
switch (param_info.param) {
case MessagePumpType::DEFAULT:
return "default_pump";
case MessagePumpType::IO:
return "IO_pump";
case MessagePumpType::UI:
return "UI_pump";
case MessagePumpType::CUSTOM:
break;
#if BUILDFLAG(IS_ANDROID)
case MessagePumpType::JAVA:
break;
#endif // BUILDFLAG(IS_ANDROID)
#if BUILDFLAG(IS_APPLE)
case MessagePumpType::NS_RUNLOOP:
break;
#endif // BUILDFLAG(IS_APPLE)
}
NOTREACHED();
return "";
}
};
TEST_P(SingleThreadTaskExecutorTypedTest, PostTask) {
SingleThreadTaskExecutor executor(GetParam());
// Add tests to message loop
scoped_refptr<Foo> foo(new Foo());
std::string a("a"), b("b"), c("c"), d("d");
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&Foo::Test0, foo));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&Foo::Test1ConstRef, foo, a));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&Foo::Test1Ptr, foo, &b));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&Foo::Test1Int, foo, 100));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&Foo::Test2Ptr, foo, &a, &c));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&Foo::Test2Mixed, foo, a, &d));
// After all tests, post a message that will shut down the message loop
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&RunLoop::QuitCurrentWhenIdleDeprecated));
// Now kick things off
RunLoop().Run();
EXPECT_EQ(foo->test_count(), 105);
EXPECT_EQ(foo->result(), "abacad");
}
TEST_P(SingleThreadTaskExecutorTypedTest, PostDelayedTask_Basic) {
SingleThreadTaskExecutor executor(GetParam());
// Test that PostDelayedTask results in a delayed task.
const TimeDelta kDelay = Milliseconds(100);
int num_tasks = 1;
TimeTicks run_time;
TimeTicks time_before_run = TimeTicks::Now();
executor.task_runner()->PostDelayedTask(
FROM_HERE, BindOnce(&RecordRunTimeFunc, &run_time, &num_tasks), kDelay);
RunLoop().Run();
TimeTicks time_after_run = TimeTicks::Now();
EXPECT_EQ(0, num_tasks);
EXPECT_LT(kDelay, time_after_run - time_before_run);
}
TEST_P(SingleThreadTaskExecutorTypedTest, PostDelayedTask_InDelayOrder) {
SingleThreadTaskExecutor executor(GetParam());
// Test that two tasks with different delays run in the right order.
int num_tasks = 2;
TimeTicks run_time1, run_time2;
executor.task_runner()->PostDelayedTask(
FROM_HERE, BindOnce(&RecordRunTimeFunc, &run_time1, &num_tasks),
Milliseconds(200));
// If we get a large pause in execution (due to a context switch) here, this
// test could fail.
executor.task_runner()->PostDelayedTask(
FROM_HERE, BindOnce(&RecordRunTimeFunc, &run_time2, &num_tasks),
Milliseconds(10));
RunLoop().Run();
EXPECT_EQ(0, num_tasks);
EXPECT_TRUE(run_time2 < run_time1);
}
TEST_P(SingleThreadTaskExecutorTypedTest, PostDelayedTask_InPostOrder) {
SingleThreadTaskExecutor executor(GetParam());
// Test that two tasks with the same delay run in the order in which they
// were posted.
//
// NOTE: This is actually an approximate test since the API only takes a
// "delay" parameter, so we are not exactly simulating two tasks that get
// posted at the exact same time. It would be nice if the API allowed us to
// specify the desired run time.
const TimeDelta kDelay = Milliseconds(100);
int num_tasks = 2;
TimeTicks run_time1, run_time2;
executor.task_runner()->PostDelayedTask(
FROM_HERE, BindOnce(&RecordRunTimeFunc, &run_time1, &num_tasks), kDelay);
executor.task_runner()->PostDelayedTask(
FROM_HERE, BindOnce(&RecordRunTimeFunc, &run_time2, &num_tasks), kDelay);
RunLoop().Run();
EXPECT_EQ(0, num_tasks);
EXPECT_TRUE(run_time1 < run_time2);
}
TEST_P(SingleThreadTaskExecutorTypedTest, PostDelayedTask_InPostOrder_2) {
SingleThreadTaskExecutor executor(GetParam());
// Test that a delayed task still runs after a normal tasks even if the
// normal tasks take a long time to run.
const TimeDelta kPause = Milliseconds(50);
int num_tasks = 2;
TimeTicks run_time;
executor.task_runner()->PostTask(FROM_HERE,
BindOnce(&SlowFunc, kPause, &num_tasks));
executor.task_runner()->PostDelayedTask(
FROM_HERE, BindOnce(&RecordRunTimeFunc, &run_time, &num_tasks),
Milliseconds(10));
TimeTicks time_before_run = TimeTicks::Now();
RunLoop().Run();
TimeTicks time_after_run = TimeTicks::Now();
EXPECT_EQ(0, num_tasks);
EXPECT_LT(kPause, time_after_run - time_before_run);
}
TEST_P(SingleThreadTaskExecutorTypedTest, PostDelayedTask_InPostOrder_3) {
SingleThreadTaskExecutor executor(GetParam());
// Test that a delayed task still runs after a pile of normal tasks. The key
// difference between this test and the previous one is that here we return
// the SingleThreadTaskExecutor a lot so we give the SingleThreadTaskExecutor
// plenty of opportunities to maybe run the delayed task. It should know not
// to do so until the delayed task's delay has passed.
int num_tasks = 11;
TimeTicks run_time1, run_time2;
// Clutter the ML with tasks.
for (int i = 1; i < num_tasks; ++i)
executor.task_runner()->PostTask(
FROM_HERE, BindOnce(&RecordRunTimeFunc, &run_time1, &num_tasks));
executor.task_runner()->PostDelayedTask(
FROM_HERE, BindOnce(&RecordRunTimeFunc, &run_time2, &num_tasks),
Milliseconds(1));
RunLoop().Run();
EXPECT_EQ(0, num_tasks);
EXPECT_TRUE(run_time2 > run_time1);
}
TEST_P(SingleThreadTaskExecutorTypedTest, PostDelayedTask_SharedTimer) {
SingleThreadTaskExecutor executor(GetParam());
// Test that the interval of the timer, used to run the next delayed task, is
// set to a value corresponding to when the next delayed task should run.
// By setting num_tasks to 1, we ensure that the first task to run causes the
// run loop to exit.
int num_tasks = 1;
TimeTicks run_time1, run_time2;
executor.task_runner()->PostDelayedTask(
FROM_HERE, BindOnce(&RecordRunTimeFunc, &run_time1, &num_tasks),
Seconds(1000));
executor.task_runner()->PostDelayedTask(
FROM_HERE, BindOnce(&RecordRunTimeFunc, &run_time2, &num_tasks),
Milliseconds(10));
TimeTicks start_time = TimeTicks::Now();
RunLoop().Run();
EXPECT_EQ(0, num_tasks);
// Ensure that we ran in far less time than the slower timer.
TimeDelta total_time = TimeTicks::Now() - start_time;
EXPECT_GT(5000, total_time.InMilliseconds());
// In case both timers somehow run at nearly the same time, sleep a little
// and then run all pending to force them both to have run. This is just
// encouraging flakiness if there is any.
PlatformThread::Sleep(Milliseconds(100));
RunLoop().RunUntilIdle();
EXPECT_TRUE(run_time1.is_null());
EXPECT_FALSE(run_time2.is_null());
}
namespace {
// This is used to inject a test point for recording the destructor calls for
// Closure objects send to MessageLoop::PostTask(). It is awkward usage since we
// are trying to hook the actual destruction, which is not a common operation.
class RecordDeletionProbe : public RefCounted<RecordDeletionProbe> {
public:
RecordDeletionProbe(RecordDeletionProbe* post_on_delete, bool* was_deleted)
: post_on_delete_(post_on_delete), was_deleted_(was_deleted) {}
void Run() {}
private:
friend class RefCounted<RecordDeletionProbe>;
~RecordDeletionProbe() {
*was_deleted_ = true;
if (post_on_delete_.get())
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&RecordDeletionProbe::Run, post_on_delete_));
}
scoped_refptr<RecordDeletionProbe> post_on_delete_;
raw_ptr<bool> was_deleted_;
};
} // namespace
/* TODO(darin): SingleThreadTaskExecutor does not support deleting all tasks in
*/
/* the destructor. */
/* Fails, http://crbug.com/50272. */
TEST_P(SingleThreadTaskExecutorTypedTest, DISABLED_EnsureDeletion) {
bool a_was_deleted = false;
bool b_was_deleted = false;
{
SingleThreadTaskExecutor executor(GetParam());
executor.task_runner()->PostTask(
FROM_HERE, BindOnce(&RecordDeletionProbe::Run,
new RecordDeletionProbe(nullptr, &a_was_deleted)));
// TODO(ajwong): Do we really need 1000ms here?
executor.task_runner()->PostDelayedTask(
FROM_HERE,
BindOnce(&RecordDeletionProbe::Run,
new RecordDeletionProbe(nullptr, &b_was_deleted)),
Milliseconds(1000));
}
EXPECT_TRUE(a_was_deleted);
EXPECT_TRUE(b_was_deleted);
}
/* TODO(darin): SingleThreadTaskExecutor does not support deleting all tasks in
*/
/* the destructor. */
/* Fails, http://crbug.com/50272. */
TEST_P(SingleThreadTaskExecutorTypedTest, DISABLED_EnsureDeletion_Chain) {
bool a_was_deleted = false;
bool b_was_deleted = false;
bool c_was_deleted = false;
{
SingleThreadTaskExecutor executor(GetParam());
// The scoped_refptr for each of the below is held either by the chained
// RecordDeletionProbe, or the bound RecordDeletionProbe::Run() callback.
RecordDeletionProbe* a = new RecordDeletionProbe(nullptr, &a_was_deleted);
RecordDeletionProbe* b = new RecordDeletionProbe(a, &b_was_deleted);
RecordDeletionProbe* c = new RecordDeletionProbe(b, &c_was_deleted);
executor.task_runner()->PostTask(FROM_HERE,
BindOnce(&RecordDeletionProbe::Run, c));
}
EXPECT_TRUE(a_was_deleted);
EXPECT_TRUE(b_was_deleted);
EXPECT_TRUE(c_was_deleted);
}
namespace {
void NestingFunc(int* depth) {
if (*depth > 0) {
*depth -= 1;
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&NestingFunc, depth));
RunLoop(RunLoop::Type::kNestableTasksAllowed).Run();
}
base::RunLoop::QuitCurrentWhenIdleDeprecated();
}
} // namespace
TEST_P(SingleThreadTaskExecutorTypedTest, Nesting) {
SingleThreadTaskExecutor executor(GetParam());
int depth = 50;
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&NestingFunc, &depth));
RunLoop().Run();
EXPECT_EQ(depth, 0);
}
TEST_P(SingleThreadTaskExecutorTypedTest, Recursive) {
SingleThreadTaskExecutor executor(GetParam());
TaskList order;
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&RecursiveFunc, &order, 1, 2));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&RecursiveFunc, &order, 2, 2));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&QuitFunc, &order, 3));
RunLoop().Run();
// FIFO order.
ASSERT_EQ(14U, order.Size());
EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
EXPECT_EQ(order.Get(2), TaskItem(RECURSIVE, 2, true));
EXPECT_EQ(order.Get(3), TaskItem(RECURSIVE, 2, false));
EXPECT_EQ(order.Get(4), TaskItem(QUITMESSAGELOOP, 3, true));
EXPECT_EQ(order.Get(5), TaskItem(QUITMESSAGELOOP, 3, false));
EXPECT_EQ(order.Get(6), TaskItem(RECURSIVE, 1, true));
EXPECT_EQ(order.Get(7), TaskItem(RECURSIVE, 1, false));
EXPECT_EQ(order.Get(8), TaskItem(RECURSIVE, 2, true));
EXPECT_EQ(order.Get(9), TaskItem(RECURSIVE, 2, false));
EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, true));
EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 1, false));
EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 2, true));
EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 2, false));
}
namespace {
void OrderedFunc(TaskList* order, int cookie) {
order->RecordStart(ORDERED, cookie);
order->RecordEnd(ORDERED, cookie);
}
} // namespace
// Tests that non nestable tasks run in FIFO if there are no nested loops.
TEST_P(SingleThreadTaskExecutorTypedTest, NonNestableWithNoNesting) {
SingleThreadTaskExecutor executor(GetParam());
TaskList order;
SingleThreadTaskRunner::GetCurrentDefault()->PostNonNestableTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 1));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 2));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&QuitFunc, &order, 3));
RunLoop().Run();
// FIFO order.
ASSERT_EQ(6U, order.Size());
EXPECT_EQ(order.Get(0), TaskItem(ORDERED, 1, true));
EXPECT_EQ(order.Get(1), TaskItem(ORDERED, 1, false));
EXPECT_EQ(order.Get(2), TaskItem(ORDERED, 2, true));
EXPECT_EQ(order.Get(3), TaskItem(ORDERED, 2, false));
EXPECT_EQ(order.Get(4), TaskItem(QUITMESSAGELOOP, 3, true));
EXPECT_EQ(order.Get(5), TaskItem(QUITMESSAGELOOP, 3, false));
}
namespace {
void FuncThatPumps(TaskList* order, int cookie) {
order->RecordStart(PUMPS, cookie);
RunLoop(RunLoop::Type::kNestableTasksAllowed).RunUntilIdle();
order->RecordEnd(PUMPS, cookie);
}
void SleepFunc(TaskList* order, int cookie, TimeDelta delay) {
order->RecordStart(SLEEP, cookie);
PlatformThread::Sleep(delay);
order->RecordEnd(SLEEP, cookie);
}
} // namespace
// Tests that non nestable tasks don't run when there's code in the call stack.
TEST_P(SingleThreadTaskExecutorTypedTest, NonNestableDelayedInNestedLoop) {
SingleThreadTaskExecutor executor(GetParam());
TaskList order;
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&FuncThatPumps, &order, 1));
SingleThreadTaskRunner::GetCurrentDefault()->PostNonNestableTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 2));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 3));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&SleepFunc, &order, 4, Milliseconds(50)));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 5));
SingleThreadTaskRunner::GetCurrentDefault()->PostNonNestableTask(
FROM_HERE, BindOnce(&QuitFunc, &order, 6));
RunLoop().Run();
// FIFO order.
ASSERT_EQ(12U, order.Size());
EXPECT_EQ(order.Get(0), TaskItem(PUMPS, 1, true));
EXPECT_EQ(order.Get(1), TaskItem(ORDERED, 3, true));
EXPECT_EQ(order.Get(2), TaskItem(ORDERED, 3, false));
EXPECT_EQ(order.Get(3), TaskItem(SLEEP, 4, true));
EXPECT_EQ(order.Get(4), TaskItem(SLEEP, 4, false));
EXPECT_EQ(order.Get(5), TaskItem(ORDERED, 5, true));
EXPECT_EQ(order.Get(6), TaskItem(ORDERED, 5, false));
EXPECT_EQ(order.Get(7), TaskItem(PUMPS, 1, false));
EXPECT_EQ(order.Get(8), TaskItem(ORDERED, 2, true));
EXPECT_EQ(order.Get(9), TaskItem(ORDERED, 2, false));
EXPECT_EQ(order.Get(10), TaskItem(QUITMESSAGELOOP, 6, true));
EXPECT_EQ(order.Get(11), TaskItem(QUITMESSAGELOOP, 6, false));
}
namespace {
void FuncThatRuns(TaskList* order, int cookie, RunLoop* run_loop) {
order->RecordStart(RUNS, cookie);
run_loop->Run();
order->RecordEnd(RUNS, cookie);
}
void FuncThatQuitsNow() {
base::RunLoop::QuitCurrentDeprecated();
}
} // namespace
// Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
TEST_P(SingleThreadTaskExecutorTypedTest, QuitNow) {
SingleThreadTaskExecutor executor(GetParam());
TaskList order;
RunLoop nested_run_loop(RunLoop::Type::kNestableTasksAllowed);
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
BindOnce(&FuncThatRuns, &order, 1, Unretained(&nested_run_loop)));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 2));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&FuncThatQuitsNow));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 3));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&FuncThatQuitsNow));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 4)); // never runs
RunLoop().Run();
ASSERT_EQ(6U, order.Size());
int task_index = 0;
EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 3, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 3, false));
EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
}
// Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
TEST_P(SingleThreadTaskExecutorTypedTest, RunLoopQuitTop) {
SingleThreadTaskExecutor executor(GetParam());
TaskList order;
RunLoop outer_run_loop;
RunLoop nested_run_loop(RunLoop::Type::kNestableTasksAllowed);
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
BindOnce(&FuncThatRuns, &order, 1, Unretained(&nested_run_loop)));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, outer_run_loop.QuitClosure());
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 2));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, nested_run_loop.QuitClosure());
outer_run_loop.Run();
ASSERT_EQ(4U, order.Size());
int task_index = 0;
EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
}
// Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
TEST_P(SingleThreadTaskExecutorTypedTest, RunLoopQuitNested) {
SingleThreadTaskExecutor executor(GetParam());
TaskList order;
RunLoop outer_run_loop;
RunLoop nested_run_loop(RunLoop::Type::kNestableTasksAllowed);
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
BindOnce(&FuncThatRuns, &order, 1, Unretained(&nested_run_loop)));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, nested_run_loop.QuitClosure());
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 2));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, outer_run_loop.QuitClosure());
outer_run_loop.Run();
ASSERT_EQ(4U, order.Size());
int task_index = 0;
EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
}
// Quits current loop and immediately runs a nested loop.
void QuitAndRunNestedLoop(TaskList* order,
int cookie,
RunLoop* outer_run_loop,
RunLoop* nested_run_loop) {
order->RecordStart(RUNS, cookie);
outer_run_loop->Quit();
nested_run_loop->Run();
order->RecordEnd(RUNS, cookie);
}
// Test that we can run nested loop after quitting the current one.
TEST_P(SingleThreadTaskExecutorTypedTest, RunLoopNestedAfterQuit) {
SingleThreadTaskExecutor executor(GetParam());
TaskList order;
RunLoop outer_run_loop;
RunLoop nested_run_loop;
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, nested_run_loop.QuitClosure());
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&QuitAndRunNestedLoop, &order, 1, &outer_run_loop,
&nested_run_loop));
outer_run_loop.Run();
ASSERT_EQ(2U, order.Size());
int task_index = 0;
EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
}
// Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
TEST_P(SingleThreadTaskExecutorTypedTest, RunLoopQuitBogus) {
SingleThreadTaskExecutor executor(GetParam());
TaskList order;
RunLoop outer_run_loop;
RunLoop nested_run_loop(RunLoop::Type::kNestableTasksAllowed);
RunLoop bogus_run_loop;
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
BindOnce(&FuncThatRuns, &order, 1, Unretained(&nested_run_loop)));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, bogus_run_loop.QuitClosure());
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 2));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, outer_run_loop.QuitClosure());
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, nested_run_loop.QuitClosure());
outer_run_loop.Run();
ASSERT_EQ(4U, order.Size());
int task_index = 0;
EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
}
// Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
TEST_P(SingleThreadTaskExecutorTypedTest, RunLoopQuitDeep) {
SingleThreadTaskExecutor executor(GetParam());
TaskList order;
RunLoop outer_run_loop;
RunLoop nested_loop1(RunLoop::Type::kNestableTasksAllowed);
RunLoop nested_loop2(RunLoop::Type::kNestableTasksAllowed);
RunLoop nested_loop3(RunLoop::Type::kNestableTasksAllowed);
RunLoop nested_loop4(RunLoop::Type::kNestableTasksAllowed);
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&FuncThatRuns, &order, 1, Unretained(&nested_loop1)));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&FuncThatRuns, &order, 2, Unretained(&nested_loop2)));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&FuncThatRuns, &order, 3, Unretained(&nested_loop3)));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&FuncThatRuns, &order, 4, Unretained(&nested_loop4)));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 5));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, outer_run_loop.QuitClosure());
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 6));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, nested_loop1.QuitClosure());
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 7));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, nested_loop2.QuitClosure());
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 8));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, nested_loop3.QuitClosure());
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 9));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, nested_loop4.QuitClosure());
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 10));
outer_run_loop.Run();
ASSERT_EQ(18U, order.Size());
int task_index = 0;
EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 2, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 3, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 4, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 5, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 5, false));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 6, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 6, false));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 7, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 7, false));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 8, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 8, false));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 9, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 9, false));
EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 4, false));
EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 3, false));
EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 2, false));
EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
}
// Tests RunLoopQuit works before RunWithID.
TEST_P(SingleThreadTaskExecutorTypedTest, RunLoopQuitOrderBefore) {
SingleThreadTaskExecutor executor(GetParam());
TaskList order;
RunLoop run_loop;
run_loop.Quit();
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 1)); // never runs
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&FuncThatQuitsNow)); // never runs
run_loop.Run();
ASSERT_EQ(0U, order.Size());
}
// Tests RunLoopQuit works during RunWithID.
TEST_P(SingleThreadTaskExecutorTypedTest, RunLoopQuitOrderDuring) {
SingleThreadTaskExecutor executor(GetParam());
TaskList order;
RunLoop run_loop;
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 1));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(FROM_HERE,
run_loop.QuitClosure());
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 2)); // never runs
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&FuncThatQuitsNow)); // never runs
run_loop.Run();
ASSERT_EQ(2U, order.Size());
int task_index = 0;
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 1, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 1, false));
EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
}
// Tests RunLoopQuit works after RunWithID.
TEST_P(SingleThreadTaskExecutorTypedTest, RunLoopQuitOrderAfter) {
SingleThreadTaskExecutor executor(GetParam());
TaskList order;
RunLoop nested_run_loop(RunLoop::Type::kNestableTasksAllowed);
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
BindOnce(&FuncThatRuns, &order, 1, Unretained(&nested_run_loop)));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 2));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&FuncThatQuitsNow));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 3));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, nested_run_loop.QuitClosure()); // has no affect
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&OrderedFunc, &order, 4));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&FuncThatQuitsNow));
nested_run_loop.allow_quit_current_deprecated_ = true;
RunLoop outer_run_loop;
outer_run_loop.Run();
ASSERT_EQ(8U, order.Size());
int task_index = 0;
EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 3, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 3, false));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 4, true));
EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 4, false));
EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
}
// Regression test for crbug.com/170904 where posting tasks recursively caused
// the message loop to hang in MessagePumpGLib, due to the buffer of the
// internal pipe becoming full. Test all SingleThreadTaskExecutor types to
// ensure this issue does not exist in other MessagePumps.
//
// On Linux, the pipe buffer size is 64KiB by default. The bug caused one byte
// accumulated in the pipe per two posts, so we should repeat 128K times to
// reproduce the bug.
#if BUILDFLAG(IS_CHROMEOS)
// TODO(crbug.com/1188497): This test is unreasonably slow on CrOS and flakily
// times out (100x slower than other platforms which take < 1s to complete
// it).
#define MAYBE_RecursivePostsDoNotFloodPipe DISABLED_RecursivePostsDoNotFloodPipe
#else
#define MAYBE_RecursivePostsDoNotFloodPipe RecursivePostsDoNotFloodPipe
#endif
TEST_P(SingleThreadTaskExecutorTypedTest, MAYBE_RecursivePostsDoNotFloodPipe) {
SingleThreadTaskExecutor executor(GetParam());
const auto begin_ticks = TimeTicks::Now();
RunLoop run_loop;
Post128KTasksThenQuit(executor.task_runner().get(), begin_ticks, begin_ticks,
TimeDelta(), run_loop.QuitClosure());
run_loop.Run();
}
TEST_P(SingleThreadTaskExecutorTypedTest,
ApplicationTasksAllowedInNativeNestedLoopAtTopLevel) {
SingleThreadTaskExecutor executor(GetParam());
EXPECT_TRUE(
CurrentThread::Get()->ApplicationTasksAllowedInNativeNestedLoop());
}
// Nestable tasks shouldn't be allowed to run reentrantly by default (regression
// test for https://crbug.com/754112).
TEST_P(SingleThreadTaskExecutorTypedTest, NestableTasksDisallowedByDefault) {
SingleThreadTaskExecutor executor(GetParam());
RunLoop run_loop;
executor.task_runner()->PostTask(
FROM_HERE,
BindOnce(
[](RunLoop* run_loop) {
EXPECT_FALSE(CurrentThread::Get()
->ApplicationTasksAllowedInNativeNestedLoop());
run_loop->Quit();
},
Unretained(&run_loop)));
run_loop.Run();
}
TEST_P(SingleThreadTaskExecutorTypedTest,
NestableTasksProcessedWhenRunLoopAllows) {
SingleThreadTaskExecutor executor(GetParam());
RunLoop run_loop;
executor.task_runner()->PostTask(
FROM_HERE,
BindOnce(
[](RunLoop* run_loop) {
// This test would hang if this RunLoop wasn't of type
// kNestableTasksAllowed (i.e. this is testing that this is
// processed and doesn't hang).
RunLoop nested_run_loop(RunLoop::Type::kNestableTasksAllowed);
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
BindOnce(
[](RunLoop* nested_run_loop) {
// Each additional layer of application task nesting
// requires its own allowance. The kNestableTasksAllowed
// RunLoop allowed this task to be processed but further
// nestable tasks are by default disallowed from this
// layer.
EXPECT_FALSE(
CurrentThread::Get()
->ApplicationTasksAllowedInNativeNestedLoop());
nested_run_loop->Quit();
},
Unretained(&nested_run_loop)));
nested_run_loop.Run();
run_loop->Quit();
},
Unretained(&run_loop)));
run_loop.Run();
}
TEST_P(SingleThreadTaskExecutorTypedTest,
ApplicationTasksAllowedInNativeNestedLoopExplicitlyInScope) {
SingleThreadTaskExecutor executor(GetParam());
RunLoop run_loop;
executor.task_runner()->PostTask(
FROM_HERE,
BindOnce(
[](RunLoop* run_loop) {
{
CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop
allow_nestable_tasks;
EXPECT_TRUE(CurrentThread::Get()
->ApplicationTasksAllowedInNativeNestedLoop());
}
EXPECT_FALSE(CurrentThread::Get()
->ApplicationTasksAllowedInNativeNestedLoop());
run_loop->Quit();
},
Unretained(&run_loop)));
run_loop.Run();
}
TEST_P(SingleThreadTaskExecutorTypedTest, IsIdleForTesting) {
SingleThreadTaskExecutor executor(GetParam());
EXPECT_TRUE(CurrentThread::Get()->IsIdleForTesting());
executor.task_runner()->PostTask(FROM_HERE, BindOnce([]() {}));
executor.task_runner()->PostDelayedTask(FROM_HERE, BindOnce([]() {}),
Milliseconds(10));
EXPECT_FALSE(CurrentThread::Get()->IsIdleForTesting());
RunLoop().RunUntilIdle();
EXPECT_TRUE(CurrentThread::Get()->IsIdleForTesting());
PlatformThread::Sleep(Milliseconds(20));
EXPECT_TRUE(CurrentThread::Get()->IsIdleForTesting());
}
TEST_P(SingleThreadTaskExecutorTypedTest, IsIdleForTestingNonNestableTask) {
SingleThreadTaskExecutor executor(GetParam());
RunLoop run_loop;
EXPECT_TRUE(CurrentThread::Get()->IsIdleForTesting());
bool nested_task_run = false;
executor.task_runner()->PostTask(
FROM_HERE, BindLambdaForTesting([&]() {
RunLoop nested_run_loop(RunLoop::Type::kNestableTasksAllowed);
executor.task_runner()->PostNonNestableTask(
FROM_HERE, BindLambdaForTesting([&]() { nested_task_run = true; }));
executor.task_runner()->PostTask(
FROM_HERE, BindLambdaForTesting([&]() {
EXPECT_FALSE(nested_task_run);
EXPECT_TRUE(CurrentThread::Get()->IsIdleForTesting());
}));
nested_run_loop.RunUntilIdle();
EXPECT_FALSE(nested_task_run);
EXPECT_FALSE(CurrentThread::Get()->IsIdleForTesting());
}));
run_loop.RunUntilIdle();
EXPECT_TRUE(nested_task_run);
EXPECT_TRUE(CurrentThread::Get()->IsIdleForTesting());
}
INSTANTIATE_TEST_SUITE_P(All,
SingleThreadTaskExecutorTypedTest,
::testing::Values(MessagePumpType::DEFAULT,
MessagePumpType::UI,
MessagePumpType::IO),
SingleThreadTaskExecutorTypedTest::ParamInfoToString);
#if BUILDFLAG(IS_WIN)
// Verifies that the SingleThreadTaskExecutor ignores WM_QUIT, rather than
// quitting. Users of SingleThreadTaskExecutor typically expect to control when
// their RunLoops stop Run()ning explicitly, via QuitClosure() etc (see
// https://crbug.com/720078).
TEST(SingleThreadTaskExecutorTest, WmQuitIsIgnored) {
SingleThreadTaskExecutor executor(MessagePumpType::UI);
// Post a WM_QUIT message to the current thread.
::PostQuitMessage(0);
// Post a task to the current thread, with a small delay to make it less
// likely that we process the posted task before looking for WM_* messages.
bool task_was_run = false;
RunLoop run_loop;
executor.task_runner()->PostDelayedTask(
FROM_HERE,
BindOnce(
[](bool* flag, OnceClosure closure) {
*flag = true;
std::move(closure).Run();
},
&task_was_run, run_loop.QuitClosure()),
TestTimeouts::tiny_timeout());
// Run the loop, and ensure that the posted task is processed before we quit.
run_loop.Run();
EXPECT_TRUE(task_was_run);
}
TEST(SingleThreadTaskExecutorTest, PostDelayedTask_SharedTimer_SubPump) {
SingleThreadTaskExecutor executor(MessagePumpType::UI);
// Test that the interval of the timer, used to run the next delayed task, is
// set to a value corresponding to when the next delayed task should run.
// By setting num_tasks to 1, we ensure that the first task to run causes the
// run loop to exit.
int num_tasks = 1;
TimeTicks run_time;
RunLoop run_loop;
executor.task_runner()->PostTask(
FROM_HERE, BindOnce(&SubPumpFunc, run_loop.QuitClosure()));
// This very delayed task should never run.
executor.task_runner()->PostDelayedTask(
FROM_HERE, BindOnce(&RecordRunTimeFunc, &run_time, &num_tasks),
Seconds(1000));
// This slightly delayed task should run from within SubPumpFunc.
executor.task_runner()->PostDelayedTask(
FROM_HERE, BindOnce(&::PostQuitMessage, 0), Milliseconds(10));
Time start_time = Time::Now();
run_loop.Run();
EXPECT_EQ(1, num_tasks);
// Ensure that we ran in far less time than the slower timer.
TimeDelta total_time = Time::Now() - start_time;
EXPECT_GT(5000, total_time.InMilliseconds());
// In case both timers somehow run at nearly the same time, sleep a little
// and then run all pending to force them both to have run. This is just
// encouraging flakiness if there is any.
PlatformThread::Sleep(Milliseconds(100));
RunLoop().RunUntilIdle();
EXPECT_TRUE(run_time.is_null());
}
namespace {
// When this fires (per the associated WM_TIMER firing), it posts an
// application task to quit the native loop.
bool QuitOnSystemTimer(UINT message,
WPARAM wparam,
LPARAM lparam,
LRESULT* result) {
if (message == static_cast<UINT>(WM_TIMER)) {
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&::PostQuitMessage, 0));
}
*result = 0;
return true;
}
// When this fires (per the associated WM_TIMER firing), it posts a delayed
// application task to quit the native loop.
bool DelayedQuitOnSystemTimer(UINT message,
WPARAM wparam,
LPARAM lparam,
LRESULT* result) {
if (message == static_cast<UINT>(WM_TIMER)) {
SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, BindOnce(&::PostQuitMessage, 0), Milliseconds(10));
}
*result = 0;
return true;
}
} // namespace
// This is a regression test for
// https://crrev.com/c/1455266/9/base/message_loop/message_pump_win.cc#125
// See below for the delayed task version.
TEST(SingleThreadTaskExecutorTest, PostImmediateTaskFromSystemPump) {
SingleThreadTaskExecutor executor(MessagePumpType::UI);
RunLoop run_loop;
// A native message window to generate a system message which invokes
// QuitOnSystemTimer() when the native timer fires.
win::MessageWindow local_message_window;
local_message_window.Create(BindRepeating(&QuitOnSystemTimer));
ASSERT_TRUE(::SetTimer(local_message_window.hwnd(), 0, 20, nullptr));
// The first task will enter a native message loop. This test then verifies
// that the pump is able to run an immediate application task after the native
// pump went idle.
executor.task_runner()->PostTask(
FROM_HERE, BindOnce(&SubPumpFunc, run_loop.QuitClosure()));
// Test success is determined by not hanging in this Run() call.
run_loop.Run();
}
// This is a regression test for
// https://crrev.com/c/1455266/9/base/message_loop/message_pump_win.cc#125 This
// is the delayed task equivalent of the above PostImmediateTaskFromSystemPump
// test.
//
// As a reminder of how this works, here's the sequence of events in this test:
// 1) Test start:
// work_deduplicator.cc(24): BindToCurrentThread
// work_deduplicator.cc(34): OnWorkRequested
// thread_controller_with_message_pump_impl.cc(237) : DoWork
// work_deduplicator.cc(50): OnWorkStarted
// 2) SubPumpFunc entered:
// message_loop_unittest.cc(278): SubPumpFunc
// 3) ScopedAllowApplicationTasksInNativeNestedLoop triggers nested
// ScheduleWork: work_deduplicator.cc(34): OnWorkRequested
// 4) Nested system loop starts and pumps internal kMsgHaveWork:
// message_loop_unittest.cc(282): SubPumpFunc : Got Message
// message_pump_win.cc(302): HandleWorkMessage
// thread_controller_with_message_pump_impl.cc(237) : DoWork
// 5) Attempt to DoWork(), there's nothing to do, NextWorkInfo indicates delay.
// work_deduplicator.cc(50): OnWorkStarted
// work_deduplicator.cc(58): WillCheckForMoreWork
// work_deduplicator.cc(67): DidCheckForMoreWork
// 6) Return control to HandleWorkMessage() which schedules native timer
// and goes to sleep (no kMsgHaveWork in native queue).
// message_pump_win.cc(328): HandleWorkMessage ScheduleNativeTimer
// 7) Native timer fires and posts the delayed application task:
// message_loop_unittest.cc(282): SubPumpFunc : Got Message
// message_loop_unittest.cc(1581): DelayedQuitOnSystemTimer
// !! This is the critical step verified by this test. Since the
// ThreadController is idle after (6), it won't be invoked again and thus
// won't get a chance to return a NextWorkInfo that indicates the next
// delay. A native timer is thus required to have SubPumpFunc handle it.
// work_deduplicator.cc(42): OnDelayedWorkRequested
// message_pump_win.cc(129): ScheduleDelayedWork
// 9) The scheduled native timer fires and runs application task binding
// ::PostQuitMessage :
// message_loop_unittest.cc(282) SubPumpFunc : Got Message
// work_deduplicator.cc(50): OnWorkStarted
// thread_controller_with_message_pump_impl.cc(237) : DoWork
// 10) SequenceManager updates delay to none and notifies
// (TODO(scheduler-dev): Could remove this step but WorkDeduplicator knows
// to ignore at least):
// work_deduplicator.cc(42): OnDelayedWorkRequested
// 11) Nested application task completes and SubPumpFunc unwinds:
// work_deduplicator.cc(58): WillCheckForMoreWork
// work_deduplicator.cc(67): DidCheckForMoreWork
// 12) ~ScopedAllowApplicationTasksInNativeNestedLoop() makes sure
// WorkDeduplicator knows we're back in DoWork() (not relevant in this test
// but important overall). work_deduplicator.cc(50): OnWorkStarted
// 13) Application task which ran SubPumpFunc completes and test finishes.
// work_deduplicator.cc(67): DidCheckForMoreWork
TEST(SingleThreadTaskExecutorTest, PostDelayedTaskFromSystemPump) {
SingleThreadTaskExecutor executor(MessagePumpType::UI);
RunLoop run_loop;
// A native message window to generate a system message which invokes
// DelayedQuitOnSystemTimer() when the native timer fires.
win::MessageWindow local_message_window;
local_message_window.Create(BindRepeating(&DelayedQuitOnSystemTimer));
ASSERT_TRUE(::SetTimer(local_message_window.hwnd(), 0, 20, nullptr));
// The first task will enter a native message loop. This test then verifies
// that the pump is able to run a delayed application task after the native
// pump went idle.
executor.task_runner()->PostTask(
FROM_HERE, BindOnce(&SubPumpFunc, run_loop.QuitClosure()));
// Test success is determined by not hanging in this Run() call.
run_loop.Run();
}
TEST(SingleThreadTaskExecutorTest, WmQuitIsVisibleToSubPump) {
SingleThreadTaskExecutor executor(MessagePumpType::UI);
// Regression test for https://crbug.com/888559. When processing a
// kMsgHaveWork we peek and remove the next message and dispatch that ourself,
// to minimize impact of these messages on message-queue processing. If we
// received kMsgHaveWork dispatched by a nested pump (e.g. ::GetMessage()
// loop) then there is a risk that the next message is that loop's WM_QUIT
// message, which must be processed directly by ::GetMessage() for the loop to
// actually quit. This test verifies that WM_QUIT exits works as expected even
// if it happens to immediately follow a kMsgHaveWork in the queue.
RunLoop run_loop;
// This application task will enter the subpump.
executor.task_runner()->PostTask(
FROM_HERE, BindOnce(&SubPumpFunc, run_loop.QuitClosure()));
// This application task will post a native WM_QUIT.
executor.task_runner()->PostTask(FROM_HERE, BindOnce(&::PostQuitMessage, 0));
// The presence of this application task means that the pump will see a
// non-empty queue after processing the previous application task (which
// posted the WM_QUIT) and hence will repost a kMsgHaveWork message in the
// native event queue. Without the fix to https://crbug.com/888559, this would
// previously result in the subpump processing kMsgHaveWork and it stealing
// the WM_QUIT message, leaving the test hung in the subpump.
executor.task_runner()->PostTask(FROM_HERE, DoNothing());
// Test success is determined by not hanging in this Run() call.
run_loop.Run();
}
TEST(SingleThreadTaskExecutorTest,
RepostingWmQuitDoesntStarveUpcomingNativeLoop) {
SingleThreadTaskExecutor executor(MessagePumpType::UI);
// This test ensures that application tasks are being processed by the native
// subpump despite the kMsgHaveWork event having already been consumed by the
// time the subpump is entered. This is subtly enforced by
// CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop which
// will ScheduleWork() upon construction (and if it's absent, the
// SingleThreadTaskExecutor shouldn't process application tasks so
// kMsgHaveWork is irrelevant). Note: This test also fails prior to the fix
// for https://crbug.com/888559 (in fact, the last two tasks are sufficient as
// a regression test), probably because of a dangling kMsgHaveWork recreating
// the effect from
// SingleThreadTaskExecutorTest.NativeMsgProcessingDoesntStealWmQuit.
RunLoop run_loop;
// This application task will post a native WM_QUIT which will be ignored
// by the main message pump.
executor.task_runner()->PostTask(FROM_HERE, BindOnce(&::PostQuitMessage, 0));
// Make sure the pump does a few extra cycles and processes (ignores) the
// WM_QUIT.
executor.task_runner()->PostTask(FROM_HERE, DoNothing());
executor.task_runner()->PostTask(FROM_HERE, DoNothing());
// This application task will enter the subpump.
executor.task_runner()->PostTask(
FROM_HERE, BindOnce(&SubPumpFunc, run_loop.QuitClosure()));
// Post an application task that will post WM_QUIT to the nested loop. The
// test will hang if the subpump doesn't process application tasks as it
// should.
executor.task_runner()->PostTask(FROM_HERE, BindOnce(&::PostQuitMessage, 0));
// Test success is determined by not hanging in this Run() call.
run_loop.Run();
}
// TODO(https://crbug.com/890016): Enable once multiple layers of nested loops
// works.
TEST(SingleThreadTaskExecutorTest,
DISABLED_UnwindingMultipleSubPumpsDoesntStarveApplicationTasks) {
SingleThreadTaskExecutor executor(MessagePumpType::UI);
// Regression test for https://crbug.com/890016.
// Tests that the subpump is still processing application tasks after
// unwinding from nested subpumps (i.e. that they didn't consume the last
// kMsgHaveWork).
RunLoop run_loop;
// Enter multiple levels of nested subpumps.
executor.task_runner()->PostTask(
FROM_HERE, BindOnce(&SubPumpFunc, run_loop.QuitClosure()));
executor.task_runner()->PostTask(FROM_HERE,
BindOnce(&SubPumpFunc, DoNothing()));
executor.task_runner()->PostTask(FROM_HERE,
BindOnce(&SubPumpFunc, DoNothing()));
// Quit two layers (with tasks in between to allow each quit to be handled
// before continuing -- ::PostQuitMessage() sets a bit, it's not a real queued
// message :
// https://blogs.msdn.microsoft.com/oldnewthing/20051104-33/?p=33453).
executor.task_runner()->PostTask(FROM_HERE, BindOnce(&::PostQuitMessage, 0));
executor.task_runner()->PostTask(FROM_HERE, DoNothing());
executor.task_runner()->PostTask(FROM_HERE, DoNothing());
executor.task_runner()->PostTask(FROM_HERE, BindOnce(&::PostQuitMessage, 0));
executor.task_runner()->PostTask(FROM_HERE, DoNothing());
executor.task_runner()->PostTask(FROM_HERE, DoNothing());
bool last_task_ran = false;
executor.task_runner()->PostTask(
FROM_HERE, BindOnce([](bool* to_set) { *to_set = true; },
Unretained(&last_task_ran)));
executor.task_runner()->PostTask(FROM_HERE, BindOnce(&::PostQuitMessage, 0));
run_loop.Run();
EXPECT_TRUE(last_task_ran);
}
namespace {
// A side effect of this test is the generation a beep. Sorry.
void RunTest_NestingDenial2(MessagePumpType message_pump_type) {
SingleThreadTaskExecutor executor(message_pump_type);
Thread worker("NestingDenial2_worker");
Thread::Options options;
options.message_pump_type = message_pump_type;
ASSERT_EQ(true, worker.StartWithOptions(std::move(options)));
TaskList order;
win::ScopedHandle event(CreateEvent(NULL, FALSE, FALSE, NULL));
worker.task_runner()->PostTask(
FROM_HERE,
BindOnce(&RecursiveFuncWin, SingleThreadTaskRunner::GetCurrentDefault(),
event.get(), true, &order, false));
// Let the other thread execute.
WaitForSingleObject(event.get(), INFINITE);
RunLoop().Run();
ASSERT_EQ(17u, order.Size());
EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
EXPECT_EQ(order.Get(2), TaskItem(MESSAGEBOX, 2, true));
EXPECT_EQ(order.Get(3), TaskItem(MESSAGEBOX, 2, false));
EXPECT_EQ(order.Get(4), TaskItem(RECURSIVE, 3, true));
EXPECT_EQ(order.Get(5), TaskItem(RECURSIVE, 3, false));
// When EndDialogFunc is processed, the window is already dismissed, hence no
// "end" entry.
EXPECT_EQ(order.Get(6), TaskItem(ENDDIALOG, 4, true));
EXPECT_EQ(order.Get(7), TaskItem(QUITMESSAGELOOP, 5, true));
EXPECT_EQ(order.Get(8), TaskItem(QUITMESSAGELOOP, 5, false));
EXPECT_EQ(order.Get(9), TaskItem(RECURSIVE, 1, true));
EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, false));
EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 3, true));
EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 3, false));
EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 1, true));
EXPECT_EQ(order.Get(14), TaskItem(RECURSIVE, 1, false));
EXPECT_EQ(order.Get(15), TaskItem(RECURSIVE, 3, true));
EXPECT_EQ(order.Get(16), TaskItem(RECURSIVE, 3, false));
}
} // namespace
// This test occasionally hangs, would need to be turned into an
// interactive_ui_test, see http://crbug.com/44567.
TEST(SingleThreadTaskExecutorTest, DISABLED_NestingDenial2) {
RunTest_NestingDenial2(MessagePumpType::DEFAULT);
RunTest_NestingDenial2(MessagePumpType::UI);
RunTest_NestingDenial2(MessagePumpType::IO);
}
// A side effect of this test is the generation a beep. Sorry. This test also
// needs to process windows messages on the current thread.
TEST(SingleThreadTaskExecutorTest, NestingSupport2) {
SingleThreadTaskExecutor executor(MessagePumpType::UI);
Thread worker("NestingSupport2_worker");
Thread::Options options;
options.message_pump_type = MessagePumpType::UI;
ASSERT_EQ(true, worker.StartWithOptions(std::move(options)));
TaskList order;
win::ScopedHandle event(CreateEvent(NULL, FALSE, FALSE, NULL));
worker.task_runner()->PostTask(
FROM_HERE,
BindOnce(&RecursiveFuncWin, SingleThreadTaskRunner::GetCurrentDefault(),
event.get(), false, &order, true));
// Let the other thread execute.
WaitForSingleObject(event.get(), INFINITE);
RunLoop().Run();
ASSERT_EQ(18u, order.Size());
EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
EXPECT_EQ(order.Get(2), TaskItem(MESSAGEBOX, 2, true));
// Note that this executes in the MessageBox modal loop.
EXPECT_EQ(order.Get(3), TaskItem(RECURSIVE, 3, true));
EXPECT_EQ(order.Get(4), TaskItem(RECURSIVE, 3, false));
EXPECT_EQ(order.Get(5), TaskItem(ENDDIALOG, 4, true));
EXPECT_EQ(order.Get(6), TaskItem(ENDDIALOG, 4, false));
EXPECT_EQ(order.Get(7), TaskItem(MESSAGEBOX, 2, false));
/* The order can subtly change here. The reason is that when RecursiveFunc(1)
is called in the main thread, if it is faster than getting to the
PostTask(FROM_HERE, BindOnce(&QuitFunc) execution, the order of task
execution can change. We don't care anyway that the order isn't correct.
EXPECT_EQ(order.Get(8), TaskItem(QUITMESSAGELOOP, 5, true));
EXPECT_EQ(order.Get(9), TaskItem(QUITMESSAGELOOP, 5, false));
EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, true));
EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 1, false));
*/
EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 3, true));
EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 3, false));
EXPECT_EQ(order.Get(14), TaskItem(RECURSIVE, 1, true));
EXPECT_EQ(order.Get(15), TaskItem(RECURSIVE, 1, false));
EXPECT_EQ(order.Get(16), TaskItem(RECURSIVE, 3, true));
EXPECT_EQ(order.Get(17), TaskItem(RECURSIVE, 3, false));
}
#endif // BUILDFLAG(IS_WIN)
#if BUILDFLAG(IS_WIN)
TEST(SingleThreadTaskExecutorTest, IOHandler) {
RunTest_IOHandler();
}
#endif // BUILDFLAG(IS_WIN)
namespace {
// Inject a test point for recording the destructor calls for Closure objects
// send to MessageLoop::PostTask(). It is awkward usage since we are trying to
// hook the actual destruction, which is not a common operation.
class DestructionObserverProbe : public RefCounted<DestructionObserverProbe> {
public:
DestructionObserverProbe(bool* task_destroyed,
bool* destruction_observer_called)
: task_destroyed_(task_destroyed),
destruction_observer_called_(destruction_observer_called) {}
virtual void Run() {
// This task should never run.
ADD_FAILURE();
}
private:
friend class RefCounted<DestructionObserverProbe>;
virtual ~DestructionObserverProbe() {
EXPECT_FALSE(*destruction_observer_called_);
*task_destroyed_ = true;
}
raw_ptr<bool> task_destroyed_;
raw_ptr<bool> destruction_observer_called_;
};
class MLDestructionObserver : public CurrentThread::DestructionObserver {
public:
MLDestructionObserver(bool* task_destroyed, bool* destruction_observer_called)
: task_destroyed_(task_destroyed),
destruction_observer_called_(destruction_observer_called),
task_destroyed_before_message_loop_(false) {}
void WillDestroyCurrentMessageLoop() override {
task_destroyed_before_message_loop_ = *task_destroyed_;
*destruction_observer_called_ = true;
}
bool task_destroyed_before_message_loop() const {
return task_destroyed_before_message_loop_;
}
private:
raw_ptr<bool> task_destroyed_;
raw_ptr<bool> destruction_observer_called_;
bool task_destroyed_before_message_loop_;
};
} // namespace
TEST(SingleThreadTaskExecutorTest, DestructionObserverTest) {
// Verify that the destruction observer gets called at the very end (after
// all the pending tasks have been destroyed).
auto executor = std::make_unique<SingleThreadTaskExecutor>();
const TimeDelta kDelay = Milliseconds(100);
bool task_destroyed = false;
bool destruction_observer_called = false;
MLDestructionObserver observer(&task_destroyed, &destruction_observer_called);
CurrentThread::Get()->AddDestructionObserver(&observer);
executor->task_runner()->PostDelayedTask(
FROM_HERE,
BindOnce(&DestructionObserverProbe::Run,
base::MakeRefCounted<DestructionObserverProbe>(
&task_destroyed, &destruction_observer_called)),
kDelay);
executor.reset();
EXPECT_TRUE(observer.task_destroyed_before_message_loop());
// The task should have been destroyed when we deleted the loop.
EXPECT_TRUE(task_destroyed);
EXPECT_TRUE(destruction_observer_called);
}
// Verify that SingleThreadTaskExecutor sets ThreadMainTaskRunner::current() and
// it posts tasks on that message loop.
TEST(SingleThreadTaskExecutorTest, ThreadMainTaskRunner) {
SingleThreadTaskExecutor executor;
scoped_refptr<Foo> foo(new Foo());
std::string a("a");
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&Foo::Test1ConstRef, foo, a));
// Post quit task;
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindOnce(&RunLoop::QuitCurrentWhenIdleDeprecated));
// Now kick things off
RunLoop().Run();
EXPECT_EQ(foo->test_count(), 1);
EXPECT_EQ(foo->result(), "a");
}
TEST(SingleThreadTaskExecutorTest, type) {
SingleThreadTaskExecutor executor(MessagePumpType::UI);
EXPECT_EQ(executor.type(), MessagePumpType::UI);
}
#if BUILDFLAG(IS_WIN)
void EmptyFunction() {}
void PostMultipleTasks() {
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&EmptyFunction));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&EmptyFunction));
}
static const int kSignalMsg = WM_USER + 2;
void PostWindowsMessage(HWND message_hwnd) {
PostMessage(message_hwnd, kSignalMsg, 0, 2);
}
void EndTest(bool* did_run, HWND hwnd) {
*did_run = true;
PostMessage(hwnd, WM_CLOSE, 0, 0);
}
int kMyMessageFilterCode = 0x5002;
LRESULT CALLBACK TestWndProcThunk(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam) {
if (message == WM_CLOSE)
EXPECT_TRUE(DestroyWindow(hwnd));
if (message != kSignalMsg)
return DefWindowProc(hwnd, message, wparam, lparam);
switch (lparam) {
case 1:
// First, we post a task that will post multiple no-op tasks to make sure
// that the pump's incoming task queue does not become empty during the
// test.
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&PostMultipleTasks));
// Next, we post a task that posts a windows message to trigger the second
// stage of the test.
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&PostWindowsMessage, hwnd));
break;
case 2:
// Since we're about to enter a modal loop, tell the message loop that we
// intend to nest tasks.
CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop
allow_nestable_tasks;
bool did_run = false;
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&EndTest, &did_run, hwnd));
// Run a nested windows-style message loop and verify that our task runs.
// If it doesn't, then we'll loop here until the test times out.
MSG msg;
while (GetMessage(&msg, 0, 0, 0)) {
if (!CallMsgFilter(&msg, kMyMessageFilterCode))
DispatchMessage(&msg);
// If this message is a WM_CLOSE, explicitly exit the modal loop.
// Posting a WM_QUIT should handle this, but unfortunately
// MessagePumpWin eats WM_QUIT messages even when running inside a modal
// loop.
if (msg.message == WM_CLOSE)
break;
}
EXPECT_TRUE(did_run);
RunLoop::QuitCurrentWhenIdleDeprecated();
break;
}
return 0;
}
TEST(SingleThreadTaskExecutorTest, AlwaysHaveUserMessageWhenNesting) {
SingleThreadTaskExecutor executor(MessagePumpType::UI);
HINSTANCE instance = CURRENT_MODULE();
WNDCLASSEX wc = {0};
wc.cbSize = sizeof(wc);
wc.lpfnWndProc = TestWndProcThunk;
wc.hInstance = instance;
wc.lpszClassName = L"SingleThreadTaskExecutorTest_HWND";
ATOM atom = RegisterClassEx(&wc);
ASSERT_TRUE(atom);
HWND message_hwnd = CreateWindow(MAKEINTATOM(atom), 0, 0, 0, 0, 0, 0,
HWND_MESSAGE, 0, instance, 0);
ASSERT_TRUE(message_hwnd) << GetLastError();
ASSERT_TRUE(PostMessage(message_hwnd, kSignalMsg, 0, 1));
RunLoop().Run();
ASSERT_TRUE(UnregisterClass(MAKEINTATOM(atom), instance));
}
#endif // BUILDFLAG(IS_WIN)
// Verify that tasks posted to and code running in the scope of the same
// SingleThreadTaskExecutor access the same SequenceLocalStorage values.
TEST(SingleThreadTaskExecutorTest, SequenceLocalStorageSetGet) {
SingleThreadTaskExecutor executor;
SequenceLocalStorageSlot<int> slot;
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindLambdaForTesting([&]() { slot.emplace(11); }));
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindLambdaForTesting([&]() { EXPECT_EQ(*slot, 11); }));
RunLoop().RunUntilIdle();
EXPECT_EQ(*slot, 11);
}
// Verify that tasks posted to and code running in different MessageLoops access
// different SequenceLocalStorage values.
TEST(SingleThreadTaskExecutorTest, SequenceLocalStorageDifferentMessageLoops) {
SequenceLocalStorageSlot<int> slot;
{
SingleThreadTaskExecutor executor;
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindLambdaForTesting([&]() { slot.emplace(11); }));
RunLoop().RunUntilIdle();
EXPECT_EQ(*slot, 11);
}
SingleThreadTaskExecutor executor;
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, BindLambdaForTesting([&]() { EXPECT_FALSE(slot); }));
RunLoop().RunUntilIdle();
EXPECT_NE(slot.GetOrCreateValue(), 11);
}
namespace {
class PostTaskOnDestroy {
public:
PostTaskOnDestroy(int times) : times_remaining_(times) {}
PostTaskOnDestroy(const PostTaskOnDestroy&) = delete;
PostTaskOnDestroy& operator=(const PostTaskOnDestroy&) = delete;
~PostTaskOnDestroy() { PostTaskWithPostingDestructor(times_remaining_); }
// Post a task that will repost itself on destruction |times| times.
static void PostTaskWithPostingDestructor(int times) {
if (times > 0) {
SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, DoNothingWithBoundArgs(
std::make_unique<PostTaskOnDestroy>(times - 1)));
}
}
private:
const int times_remaining_;
};
} // namespace
// Test that SingleThreadTaskExecutor destruction handles a task's destructor
// posting another task.
TEST(SingleThreadTaskExecutorDestructionTest,
DestroysFineWithPostTaskOnDestroy) {
SingleThreadTaskExecutor executor;
PostTaskOnDestroy::PostTaskWithPostingDestructor(10);
}
} // namespace base
|