This file is indexed.

/usr/lib/python3/dist-packages/billiard/pool.py is in python3-billiard 3.5.0.3-1.

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

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
# -*- coding: utf-8 -*-
#
# Module providing the `Pool` class for managing a process pool
#
# multiprocessing/pool.py
#
# Copyright (c) 2006-2008, R Oudkerk
# Licensed to PSF under a Contributor Agreement.
#
from __future__ import absolute_import

#
# Imports
#

import errno
import itertools
import os
import platform
import signal
import sys
import threading
import time
import warnings

from collections import deque
from functools import partial

from . import cpu_count, get_context
from . import util
from .common import (
    TERM_SIGNAL, human_status, pickle_loads, reset_signals, restart_state,
)
from .compat import get_errno, mem_rss, send_offset
from .einfo import ExceptionInfo
from .dummy import DummyProcess
from .exceptions import (
    CoroStop,
    RestartFreqExceeded,
    SoftTimeLimitExceeded,
    Terminated,
    TimeLimitExceeded,
    TimeoutError,
    WorkerLostError,
)
from .five import Empty, Queue, range, values, reraise, monotonic
from .util import Finalize, debug

MAXMEM_USED_FMT = """\
child process exiting after exceeding memory limit ({0}KiB / {1}KiB)
"""

PY3 = sys.version_info[0] == 3

if platform.system() == 'Windows':  # pragma: no cover
    # On Windows os.kill calls TerminateProcess which cannot be
    # handled by # any process, so this is needed to terminate the task
    # *and its children* (if any).
    from ._win import kill_processtree as _kill  # noqa
    SIGKILL = TERM_SIGNAL
else:
    from os import kill as _kill                 # noqa
    SIGKILL = signal.SIGKILL


try:
    TIMEOUT_MAX = threading.TIMEOUT_MAX
except AttributeError:  # pragma: no cover
    TIMEOUT_MAX = 1e10  # noqa


if sys.version_info >= (3, 3):
    _Semaphore = threading.Semaphore
else:
    # Semaphore is a factory function pointing to _Semaphore
    _Semaphore = threading._Semaphore  # noqa

#
# Constants representing the state of a pool
#

RUN = 0
CLOSE = 1
TERMINATE = 2

#
# Constants representing the state of a job
#

ACK = 0
READY = 1
TASK = 2
NACK = 3
DEATH = 4

#
# Exit code constants
#
EX_OK = 0
EX_FAILURE = 1
EX_RECYCLE = 0x9B


# Signal used for soft time limits.
SIG_SOFT_TIMEOUT = getattr(signal, "SIGUSR1", None)

#
# Miscellaneous
#

LOST_WORKER_TIMEOUT = 10.0
EX_OK = getattr(os, "EX_OK", 0)

job_counter = itertools.count()

Lock = threading.Lock


def _get_send_offset(connection):
    try:
        native = connection.send_offset
    except AttributeError:
        native = None
    if native is None:
        return partial(send_offset, connection.fileno())
    return native


def mapstar(args):
    return list(map(*args))


def starmapstar(args):
    return list(itertools.starmap(args[0], args[1]))


def error(msg, *args, **kwargs):
    util.get_logger().error(msg, *args, **kwargs)


def stop_if_not_current(thread, timeout=None):
    if thread is not threading.current_thread():
        thread.stop(timeout)


class LaxBoundedSemaphore(_Semaphore):
    """Semaphore that checks that # release is <= # acquires,
    but ignores if # releases >= value."""

    def shrink(self):
        self._initial_value -= 1
        self.acquire()

    if PY3:

        def __init__(self, value=1, verbose=None):
            _Semaphore.__init__(self, value)
            self._initial_value = value

        def grow(self):
            with self._cond:
                self._initial_value += 1
                self._value += 1
                self._cond.notify()

        def release(self):
            cond = self._cond
            with cond:
                if self._value < self._initial_value:
                    self._value += 1
                    cond.notify_all()

        def clear(self):
            while self._value < self._initial_value:
                _Semaphore.release(self)
    else:

        def __init__(self, value=1, verbose=None):
            _Semaphore.__init__(self, value, verbose)
            self._initial_value = value

        def grow(self):
            cond = self._Semaphore__cond
            with cond:
                self._initial_value += 1
                self._Semaphore__value += 1
                cond.notify()

        def release(self):  # noqa
            cond = self._Semaphore__cond
            with cond:
                if self._Semaphore__value < self._initial_value:
                    self._Semaphore__value += 1
                    cond.notifyAll()

        def clear(self):  # noqa
            while self._Semaphore__value < self._initial_value:
                _Semaphore.release(self)

#
# Exceptions
#


class MaybeEncodingError(Exception):
    """Wraps possible unpickleable errors, so they can be
    safely sent through the socket."""

    def __init__(self, exc, value):
        self.exc = repr(exc)
        self.value = repr(value)
        super(MaybeEncodingError, self).__init__(self.exc, self.value)

    def __repr__(self):
        return "<%s: %s>" % (self.__class__.__name__, str(self))

    def __str__(self):
        return "Error sending result: '%r'. Reason: '%r'." % (
            self.value, self.exc)


class WorkersJoined(Exception):
    """All workers have terminated."""


def soft_timeout_sighandler(signum, frame):
    raise SoftTimeLimitExceeded()

#
# Code run by worker processes
#


class Worker(object):

    def __init__(self, inq, outq, synq=None, initializer=None, initargs=(),
                 maxtasks=None, sentinel=None, on_exit=None,
                 sigprotection=True, wrap_exception=True,
                 max_memory_per_child=None):
        assert maxtasks is None or (type(maxtasks) == int and maxtasks > 0)
        self.initializer = initializer
        self.initargs = initargs
        self.maxtasks = maxtasks
        self.max_memory_per_child = max_memory_per_child
        self._shutdown = sentinel
        self.on_exit = on_exit
        self.sigprotection = sigprotection
        self.inq, self.outq, self.synq = inq, outq, synq
        self.wrap_exception = wrap_exception  # XXX cannot disable yet
        self.contribute_to_object(self)

    def contribute_to_object(self, obj):
        obj.inq, obj.outq, obj.synq = self.inq, self.outq, self.synq
        obj.inqW_fd = self.inq._writer.fileno()    # inqueue write fd
        obj.outqR_fd = self.outq._reader.fileno()  # outqueue read fd
        if self.synq:
            obj.synqR_fd = self.synq._reader.fileno()  # synqueue read fd
            obj.synqW_fd = self.synq._writer.fileno()  # synqueue write fd
            obj.send_syn_offset = _get_send_offset(self.synq._writer)
        else:
            obj.synqR_fd = obj.synqW_fd = obj._send_syn_offset = None
        obj._quick_put = self.inq._writer.send
        obj._quick_get = self.outq._reader.recv
        obj.send_job_offset = _get_send_offset(self.inq._writer)
        return obj

    def __reduce__(self):
        return self.__class__, (
            self.inq, self.outq, self.synq, self.initializer,
            self.initargs, self.maxtasks, self._shutdown, self.on_exit,
            self.sigprotection, self.wrap_exception,
        )

    def __call__(self):
        _exit = sys.exit
        _exitcode = [None]

        def exit(status=None):
            _exitcode[0] = status
            return _exit()
        sys.exit = exit

        pid = os.getpid()

        self._make_child_methods()
        self.after_fork()
        self.on_loop_start(pid=pid)  # callback on loop start
        try:
            sys.exit(self.workloop(pid=pid))
        except Exception as exc:
            error('Pool process %r error: %r', self, exc, exc_info=1)
            self._do_exit(pid, _exitcode[0], exc)
        finally:
            self._do_exit(pid, _exitcode[0], None)

    def _do_exit(self, pid, exitcode, exc=None):
        if exitcode is None:
            exitcode = EX_FAILURE if exc else EX_OK

        if self.on_exit is not None:
            self.on_exit(pid, exitcode)

        if sys.platform != 'win32':
            try:
                self.outq.put((DEATH, (pid, exitcode)))
                time.sleep(1)
            finally:
                os._exit(exitcode)
        else:
            os._exit(exitcode)

    def on_loop_start(self, pid):
        pass

    def prepare_result(self, result):
        return result

    def workloop(self, debug=debug, now=monotonic, pid=None):
        pid = pid or os.getpid()
        put = self.outq.put
        inqW_fd = self.inqW_fd
        synqW_fd = self.synqW_fd
        maxtasks = self.maxtasks
        max_memory_per_child = self.max_memory_per_child or 0
        prepare_result = self.prepare_result

        wait_for_job = self.wait_for_job
        _wait_for_syn = self.wait_for_syn

        def wait_for_syn(jid):
            i = 0
            while 1:
                if i > 60:
                    error('!!!WAIT FOR ACK TIMEOUT: job:%r fd:%r!!!',
                          jid, self.synq._reader.fileno(), exc_info=1)
                req = _wait_for_syn()
                if req:
                    type_, args = req
                    if type_ == NACK:
                        return False
                    assert type_ == ACK
                    return True
                i += 1

        completed = 0
        while maxtasks is None or (maxtasks and completed < maxtasks):
            req = wait_for_job()
            if req:
                type_, args_ = req
                assert type_ == TASK
                job, i, fun, args, kwargs = args_
                put((ACK, (job, i, now(), pid, synqW_fd)))
                if _wait_for_syn:
                    confirm = wait_for_syn(job)
                    if not confirm:
                        continue  # received NACK
                try:
                    result = (True, prepare_result(fun(*args, **kwargs)))
                except Exception:
                    result = (False, ExceptionInfo())
                try:
                    put((READY, (job, i, result, inqW_fd)))
                except Exception as exc:
                    _, _, tb = sys.exc_info()
                    try:
                        wrapped = MaybeEncodingError(exc, result[1])
                        einfo = ExceptionInfo((
                            MaybeEncodingError, wrapped, tb,
                        ))
                        put((READY, (job, i, (False, einfo), inqW_fd)))
                    finally:
                        del(tb)
                completed += 1
                if max_memory_per_child > 0:
                    used_kb = mem_rss()
                    if used_kb <= 0:
                        error('worker unable to determine memory usage')
                    if used_kb > 0 and used_kb > max_memory_per_child:
                        error(MAXMEM_USED_FMT.format(
                            used_kb, max_memory_per_child))
                        return EX_RECYCLE

        debug('worker exiting after %d tasks', completed)
        if maxtasks:
            return EX_RECYCLE if completed == maxtasks else EX_FAILURE
        return EX_OK

    def after_fork(self):
        if hasattr(self.inq, '_writer'):
            self.inq._writer.close()
        if hasattr(self.outq, '_reader'):
            self.outq._reader.close()

        if self.initializer is not None:
            self.initializer(*self.initargs)

        # Make sure all exiting signals call finally: blocks.
        # This is important for the semaphore to be released.
        reset_signals(full=self.sigprotection)

        # install signal handler for soft timeouts.
        if SIG_SOFT_TIMEOUT is not None:
            signal.signal(SIG_SOFT_TIMEOUT, soft_timeout_sighandler)

        try:
            signal.signal(signal.SIGINT, signal.SIG_IGN)
        except AttributeError:
            pass

    def _make_recv_method(self, conn):
        get = conn.get

        if hasattr(conn, '_reader'):
            _poll = conn._reader.poll
            if hasattr(conn, 'get_payload') and conn.get_payload:
                get_payload = conn.get_payload

                def _recv(timeout, loads=pickle_loads):
                    return True, loads(get_payload())
            else:
                def _recv(timeout):  # noqa
                    if _poll(timeout):
                        return True, get()
                    return False, None
        else:
            def _recv(timeout):  # noqa
                try:
                    return True, get(timeout=timeout)
                except Queue.Empty:
                    return False, None
        return _recv

    def _make_child_methods(self, loads=pickle_loads):
        self.wait_for_job = self._make_protected_receive(self.inq)
        self.wait_for_syn = (self._make_protected_receive(self.synq)
                             if self.synq else None)

    def _make_protected_receive(self, conn):
        _receive = self._make_recv_method(conn)
        should_shutdown = self._shutdown.is_set if self._shutdown else None

        def receive(debug=debug):
            if should_shutdown and should_shutdown():
                debug('worker got sentinel -- exiting')
                raise SystemExit(EX_OK)
            try:
                ready, req = _receive(1.0)
                if not ready:
                    return None
            except (EOFError, IOError) as exc:
                if get_errno(exc) == errno.EINTR:
                    return None  # interrupted, maybe by gdb
                debug('worker got %s -- exiting', type(exc).__name__)
                raise SystemExit(EX_FAILURE)
            if req is None:
                debug('worker got sentinel -- exiting')
                raise SystemExit(EX_FAILURE)
            return req

        return receive


#
# Class representing a process pool
#


class PoolThread(DummyProcess):

    def __init__(self, *args, **kwargs):
        DummyProcess.__init__(self)
        self._state = RUN
        self._was_started = False
        self.daemon = True

    def run(self):
        try:
            return self.body()
        except RestartFreqExceeded as exc:
            error("Thread %r crashed: %r", type(self).__name__, exc,
                  exc_info=1)
            _kill(os.getpid(), TERM_SIGNAL)
            sys.exit()
        except Exception as exc:
            error("Thread %r crashed: %r", type(self).__name__, exc,
                  exc_info=1)
            os._exit(1)

    def start(self, *args, **kwargs):
        self._was_started = True
        super(PoolThread, self).start(*args, **kwargs)

    def on_stop_not_started(self):
        pass

    def stop(self, timeout=None):
        if self._was_started:
            self.join(timeout)
            return
        self.on_stop_not_started()

    def terminate(self):
        self._state = TERMINATE

    def close(self):
        self._state = CLOSE


class Supervisor(PoolThread):

    def __init__(self, pool):
        self.pool = pool
        super(Supervisor, self).__init__()

    def body(self):
        debug('worker handler starting')

        time.sleep(0.8)

        pool = self.pool

        try:
            # do a burst at startup to verify that we can start
            # our pool processes, and in that time we lower
            # the max restart frequency.
            prev_state = pool.restart_state
            pool.restart_state = restart_state(10 * pool._processes, 1)
            for _ in range(10):
                if self._state == RUN and pool._state == RUN:
                    pool._maintain_pool()
                    time.sleep(0.1)

            # Keep maintaing workers until the cache gets drained, unless
            # the pool is termianted
            pool.restart_state = prev_state
            while self._state == RUN and pool._state == RUN:
                pool._maintain_pool()
                time.sleep(0.8)
        except RestartFreqExceeded:
            pool.close()
            pool.join()
            raise
        debug('worker handler exiting')


class TaskHandler(PoolThread):

    def __init__(self, taskqueue, put, outqueue, pool, cache):
        self.taskqueue = taskqueue
        self.put = put
        self.outqueue = outqueue
        self.pool = pool
        self.cache = cache
        super(TaskHandler, self).__init__()

    def body(self):
        cache = self.cache
        taskqueue = self.taskqueue
        put = self.put

        for taskseq, set_length in iter(taskqueue.get, None):
            task = None
            i = -1
            try:
                for i, task in enumerate(taskseq):
                    if self._state:
                        debug('task handler found thread._state != RUN')
                        break
                    try:
                        put(task)
                    except IOError:
                        debug('could not put task on queue')
                        break
                    except Exception:
                        job, ind = task[:2]
                        try:
                            cache[job]._set(ind, (False, ExceptionInfo()))
                        except KeyError:
                            pass
                else:
                    if set_length:
                        debug('doing set_length()')
                        set_length(i + 1)
                    continue
                break
            except Exception:
                job, ind = task[:2] if task else (0, 0)
                if job in cache:
                    cache[job]._set(ind + 1, (False, ExceptionInfo()))
                if set_length:
                    util.debug('doing set_length()')
                    set_length(i + 1)
        else:
            debug('task handler got sentinel')

        self.tell_others()

    def tell_others(self):
        outqueue = self.outqueue
        put = self.put
        pool = self.pool

        try:
            # tell result handler to finish when cache is empty
            debug('task handler sending sentinel to result handler')
            outqueue.put(None)

            # tell workers there is no more work
            debug('task handler sending sentinel to workers')
            for p in pool:
                put(None)
        except IOError:
            debug('task handler got IOError when sending sentinels')

        debug('task handler exiting')

    def on_stop_not_started(self):
        self.tell_others()


class TimeoutHandler(PoolThread):

    def __init__(self, processes, cache, t_soft, t_hard):
        self.processes = processes
        self.cache = cache
        self.t_soft = t_soft
        self.t_hard = t_hard
        self._it = None
        super(TimeoutHandler, self).__init__()

    def _process_by_pid(self, pid):
        return next((
            (proc, i) for i, proc in enumerate(self.processes)
            if proc.pid == pid
        ), (None, None))

    def on_soft_timeout(self, job):
        debug('soft time limit exceeded for %r', job)
        process, _index = self._process_by_pid(job._worker_pid)
        if not process:
            return

        # Run timeout callback
        job.handle_timeout(soft=True)

        try:
            _kill(job._worker_pid, SIG_SOFT_TIMEOUT)
        except OSError as exc:
            if get_errno(exc) != errno.ESRCH:
                raise

    def on_hard_timeout(self, job):
        if job.ready():
            return
        debug('hard time limit exceeded for %r', job)
        # Remove from cache and set return value to an exception
        try:
            raise TimeLimitExceeded(job._timeout)
        except TimeLimitExceeded:
            job._set(job._job, (False, ExceptionInfo()))
        else:  # pragma: no cover
            pass

        # Remove from _pool
        process, _index = self._process_by_pid(job._worker_pid)

        # Run timeout callback
        job.handle_timeout(soft=False)

        if process:
            self._trywaitkill(process)

    def _trywaitkill(self, worker):
        debug('timeout: sending TERM to %s', worker._name)
        try:
            if os.getpgid(worker.pid) == worker.pid:
                debug("worker %s is a group leader. It is safe to kill (SIGTERM) the whole group", worker.pid)
                os.killpg(os.getpgid(worker.pid), signal.SIGTERM)
            else:
                worker.terminate()
        except OSError:
            pass
        else:
            if worker._popen.wait(timeout=0.1):
                return
        debug('timeout: TERM timed-out, now sending KILL to %s', worker._name)
        try:
            if os.getpgid(worker.pid) == worker.pid:
                debug("worker %s is a group leader. It is safe to kill (SIGKILL) the whole group", worker.pid)
                os.killpg(os.getpgid(worker.pid), signal.SIGKILL)
            else:
                _kill(worker.pid, SIGKILL)
        except OSError:
            pass

    def handle_timeouts(self):
        cache = self.cache
        t_hard, t_soft = self.t_hard, self.t_soft
        dirty = set()
        on_soft_timeout = self.on_soft_timeout
        on_hard_timeout = self.on_hard_timeout

        def _timed_out(start, timeout):
            if not start or not timeout:
                return False
            if monotonic() >= start + timeout:
                return True

        # Inner-loop
        while self._state == RUN:

            # Remove dirty items not in cache anymore
            if dirty:
                dirty = set(k for k in dirty if k in cache)

            for i, job in list(cache.items()):
                ack_time = job._time_accepted
                soft_timeout = job._soft_timeout
                if soft_timeout is None:
                    soft_timeout = t_soft
                hard_timeout = job._timeout
                if hard_timeout is None:
                    hard_timeout = t_hard
                if _timed_out(ack_time, hard_timeout):
                    on_hard_timeout(job)
                elif i not in dirty and _timed_out(ack_time, soft_timeout):
                    on_soft_timeout(job)
                    dirty.add(i)
            yield

    def body(self):
        while self._state == RUN:
            try:
                for _ in self.handle_timeouts():
                    time.sleep(1.0)  # don't spin
            except CoroStop:
                break
        debug('timeout handler exiting')

    def handle_event(self, *args):
        if self._it is None:
            self._it = self.handle_timeouts()
        try:
            next(self._it)
        except StopIteration:
            self._it = None


class ResultHandler(PoolThread):

    def __init__(self, outqueue, get, cache, poll,
                 join_exited_workers, putlock, restart_state,
                 check_timeouts, on_job_ready):
        self.outqueue = outqueue
        self.get = get
        self.cache = cache
        self.poll = poll
        self.join_exited_workers = join_exited_workers
        self.putlock = putlock
        self.restart_state = restart_state
        self._it = None
        self._shutdown_complete = False
        self.check_timeouts = check_timeouts
        self.on_job_ready = on_job_ready
        self._make_methods()
        super(ResultHandler, self).__init__()

    def on_stop_not_started(self):
        # used when pool started without result handler thread.
        self.finish_at_shutdown(handle_timeouts=True)

    def _make_methods(self):
        cache = self.cache
        putlock = self.putlock
        restart_state = self.restart_state
        on_job_ready = self.on_job_ready

        def on_ack(job, i, time_accepted, pid, synqW_fd):
            restart_state.R = 0
            try:
                cache[job]._ack(i, time_accepted, pid, synqW_fd)
            except (KeyError, AttributeError):
                # Object gone or doesn't support _ack (e.g. IMAPIterator).
                pass

        def on_ready(job, i, obj, inqW_fd):
            if on_job_ready is not None:
                on_job_ready(job, i, obj, inqW_fd)
            try:
                item = cache[job]
            except KeyError:
                return
            if not item.ready():
                if putlock is not None:
                    putlock.release()
            try:
                item._set(i, obj)
            except KeyError:
                pass

        def on_death(pid, exitcode):
            try:
                os.kill(pid, TERM_SIGNAL)
            except OSError as exc:
                if get_errno(exc) != errno.ESRCH:
                    raise

        state_handlers = self.state_handlers = {
            ACK: on_ack, READY: on_ready, DEATH: on_death
        }

        def on_state_change(task):
            state, args = task
            try:
                state_handlers[state](*args)
            except KeyError:
                debug("Unknown job state: %s (args=%s)", state, args)
        self.on_state_change = on_state_change

    def _process_result(self, timeout=1.0):
        poll = self.poll
        on_state_change = self.on_state_change

        while 1:
            try:
                ready, task = poll(timeout)
            except (IOError, EOFError) as exc:
                debug('result handler got %r -- exiting', exc)
                raise CoroStop()

            if self._state:
                assert self._state == TERMINATE
                debug('result handler found thread._state=TERMINATE')
                raise CoroStop()

            if ready:
                if task is None:
                    debug('result handler got sentinel')
                    raise CoroStop()
                on_state_change(task)
                if timeout != 0:  # blocking
                    break
            else:
                break
            yield

    def handle_event(self, fileno=None, events=None):
        if self._state == RUN:
            if self._it is None:
                self._it = self._process_result(0)  # non-blocking
            try:
                next(self._it)
            except (StopIteration, CoroStop):
                self._it = None

    def body(self):
        debug('result handler starting')
        try:
            while self._state == RUN:
                try:
                    for _ in self._process_result(1.0):  # blocking
                        pass
                except CoroStop:
                    break
        finally:
            self.finish_at_shutdown()

    def finish_at_shutdown(self, handle_timeouts=False):
        self._shutdown_complete = True
        get = self.get
        outqueue = self.outqueue
        cache = self.cache
        poll = self.poll
        join_exited_workers = self.join_exited_workers
        check_timeouts = self.check_timeouts
        on_state_change = self.on_state_change

        time_terminate = None
        while cache and self._state != TERMINATE:
            if check_timeouts is not None:
                check_timeouts()
            try:
                ready, task = poll(1.0)
            except (IOError, EOFError) as exc:
                debug('result handler got %r -- exiting', exc)
                return

            if ready:
                if task is None:
                    debug('result handler ignoring extra sentinel')
                    continue

                on_state_change(task)
            try:
                join_exited_workers(shutdown=True)
            except WorkersJoined:
                now = monotonic()
                if not time_terminate:
                    time_terminate = now
                else:
                    if now - time_terminate > 5.0:
                        debug('result handler exiting: timed out')
                        break
                    debug('result handler: all workers terminated, '
                          'timeout in %ss',
                          abs(min(now - time_terminate - 5.0, 0)))

        if hasattr(outqueue, '_reader'):
            debug('ensuring that outqueue is not full')
            # If we don't make room available in outqueue then
            # attempts to add the sentinel (None) to outqueue may
            # block.  There is guaranteed to be no more than 2 sentinels.
            try:
                for i in range(10):
                    if not outqueue._reader.poll():
                        break
                    get()
            except (IOError, EOFError):
                pass

        debug('result handler exiting: len(cache)=%s, thread._state=%s',
              len(cache), self._state)


class Pool(object):
    '''
    Class which supports an async version of applying functions to arguments.
    '''
    _wrap_exception = True
    Worker = Worker
    Supervisor = Supervisor
    TaskHandler = TaskHandler
    TimeoutHandler = TimeoutHandler
    ResultHandler = ResultHandler
    SoftTimeLimitExceeded = SoftTimeLimitExceeded

    def __init__(self, processes=None, initializer=None, initargs=(),
                 maxtasksperchild=None, timeout=None, soft_timeout=None,
                 lost_worker_timeout=None,
                 max_restarts=None, max_restart_freq=1,
                 on_process_up=None,
                 on_process_down=None,
                 on_timeout_set=None,
                 on_timeout_cancel=None,
                 threads=True,
                 semaphore=None,
                 putlocks=False,
                 allow_restart=False,
                 synack=False,
                 on_process_exit=None,
                 context=None,
                 max_memory_per_child=None,
                 enable_timeouts=False,
                 **kwargs):
        self._ctx = context or get_context()
        self.synack = synack
        self._setup_queues()
        self._taskqueue = Queue()
        self._cache = {}
        self._state = RUN
        self.timeout = timeout
        self.soft_timeout = soft_timeout
        self._maxtasksperchild = maxtasksperchild
        self._max_memory_per_child = max_memory_per_child
        self._initializer = initializer
        self._initargs = initargs
        self._on_process_exit = on_process_exit
        self.lost_worker_timeout = lost_worker_timeout or LOST_WORKER_TIMEOUT
        self.on_process_up = on_process_up
        self.on_process_down = on_process_down
        self.on_timeout_set = on_timeout_set
        self.on_timeout_cancel = on_timeout_cancel
        self.threads = threads
        self.readers = {}
        self.allow_restart = allow_restart

        self.enable_timeouts = bool(
            enable_timeouts or
            self.timeout is not None or
            self.soft_timeout is not None
        )

        if soft_timeout and SIG_SOFT_TIMEOUT is None:
            warnings.warn(UserWarning(
                "Soft timeouts are not supported: "
                "on this platform: It does not have the SIGUSR1 signal.",
            ))
            soft_timeout = None

        self._processes = self.cpu_count() if processes is None else processes
        self.max_restarts = max_restarts or round(self._processes * 100)
        self.restart_state = restart_state(max_restarts, max_restart_freq or 1)

        if initializer is not None and not callable(initializer):
            raise TypeError('initializer must be a callable')

        if on_process_exit is not None and not callable(on_process_exit):
            raise TypeError('on_process_exit must be callable')

        self._Process = self._ctx.Process

        self._pool = []
        self._poolctrl = {}
        self.putlocks = putlocks
        self._putlock = semaphore or LaxBoundedSemaphore(self._processes)
        for i in range(self._processes):
            self._create_worker_process(i)

        self._worker_handler = self.Supervisor(self)
        if threads:
            self._worker_handler.start()

        self._task_handler = self.TaskHandler(self._taskqueue,
                                              self._quick_put,
                                              self._outqueue,
                                              self._pool,
                                              self._cache)
        if threads:
            self._task_handler.start()

        self.check_timeouts = None

        # Thread killing timedout jobs.
        if self.enable_timeouts:
            self._timeout_handler = self.TimeoutHandler(
                self._pool, self._cache,
                self.soft_timeout, self.timeout,
            )
            self._timeout_handler_mutex = Lock()
            self._timeout_handler_started = False
            self._start_timeout_handler()
            # If running without threads, we need to check for timeouts
            # while waiting for unfinished work at shutdown.
            if not threads:
                self.check_timeouts = self._timeout_handler.handle_event
        else:
            self._timeout_handler = None
            self._timeout_handler_started = False
            self._timeout_handler_mutex = None

        # Thread processing results in the outqueue.
        self._result_handler = self.create_result_handler()
        self.handle_result_event = self._result_handler.handle_event

        if threads:
            self._result_handler.start()

        self._terminate = Finalize(
            self, self._terminate_pool,
            args=(self._taskqueue, self._inqueue, self._outqueue,
                  self._pool, self._worker_handler, self._task_handler,
                  self._result_handler, self._cache,
                  self._timeout_handler,
                  self._help_stuff_finish_args()),
            exitpriority=15,
        )

    def Process(self, *args, **kwds):
        return self._Process(*args, **kwds)

    def WorkerProcess(self, worker):
        return worker.contribute_to_object(self.Process(target=worker))

    def create_result_handler(self, **extra_kwargs):
        return self.ResultHandler(
            self._outqueue, self._quick_get, self._cache,
            self._poll_result, self._join_exited_workers,
            self._putlock, self.restart_state, self.check_timeouts,
            self.on_job_ready, **extra_kwargs
        )

    def on_job_ready(self, job, i, obj, inqW_fd):
        pass

    def _help_stuff_finish_args(self):
        return self._inqueue, self._task_handler, self._pool

    def cpu_count(self):
        try:
            return cpu_count()
        except NotImplementedError:
            return 1

    def handle_result_event(self, *args):
        return self._result_handler.handle_event(*args)

    def _process_register_queues(self, worker, queues):
        pass

    def _process_by_pid(self, pid):
        return next((
            (proc, i) for i, proc in enumerate(self._pool)
            if proc.pid == pid
        ), (None, None))

    def get_process_queues(self):
        return self._inqueue, self._outqueue, None

    def _create_worker_process(self, i):
        sentinel = self._ctx.Event() if self.allow_restart else None
        inq, outq, synq = self.get_process_queues()
        w = self.WorkerProcess(self.Worker(
            inq, outq, synq, self._initializer, self._initargs,
            self._maxtasksperchild, sentinel, self._on_process_exit,
            # Need to handle all signals if using the ipc semaphore,
            # to make sure the semaphore is released.
            sigprotection=self.threads,
            wrap_exception=self._wrap_exception,
            max_memory_per_child=self._max_memory_per_child,
        ))
        self._pool.append(w)
        self._process_register_queues(w, (inq, outq, synq))
        w.name = w.name.replace('Process', 'PoolWorker')
        w.daemon = True
        w.index = i
        w.start()
        self._poolctrl[w.pid] = sentinel
        if self.on_process_up:
            self.on_process_up(w)
        return w

    def process_flush_queues(self, worker):
        pass

    def _join_exited_workers(self, shutdown=False):
        """Cleanup after any worker processes which have exited due to
        reaching their specified lifetime. Returns True if any workers were
        cleaned up.
        """
        now = None
        # The worker may have published a result before being terminated,
        # but we have no way to accurately tell if it did.  So we wait for
        # _lost_worker_timeout seconds before we mark the job with
        # WorkerLostError.
        for job in [job for job in list(self._cache.values())
                    if not job.ready() and job._worker_lost]:
            now = now or monotonic()
            lost_time, lost_ret = job._worker_lost
            if now - lost_time > job._lost_worker_timeout:
                self.mark_as_worker_lost(job, lost_ret)

        if shutdown and not len(self._pool):
            raise WorkersJoined()

        cleaned, exitcodes = {}, {}
        for i in reversed(range(len(self._pool))):
            worker = self._pool[i]
            exitcode = worker.exitcode
            popen = worker._popen
            if popen is None or exitcode is not None:
                # worker exited
                debug('Supervisor: cleaning up worker %d', i)
                if popen is not None:
                    worker.join()
                debug('Supervisor: worked %d joined', i)
                cleaned[worker.pid] = worker
                exitcodes[worker.pid] = exitcode
                if exitcode not in (EX_OK, EX_RECYCLE) and \
                        not getattr(worker, '_controlled_termination', False):
                    error(
                        'Process %r pid:%r exited with %r',
                        worker.name, worker.pid, human_status(exitcode),
                        exc_info=0,
                    )
                self.process_flush_queues(worker)
                del self._pool[i]
                del self._poolctrl[worker.pid]
        if cleaned:
            all_pids = [w.pid for w in self._pool]
            for job in list(self._cache.values()):
                acked_by_gone = next(
                    (pid for pid in job.worker_pids()
                     if pid in cleaned or pid not in all_pids),
                    None
                )
                # already accepted by process
                if acked_by_gone:
                    self.on_job_process_down(job, acked_by_gone)
                    if not job.ready():
                        exitcode = exitcodes.get(acked_by_gone) or 0
                        proc = cleaned.get(acked_by_gone)
                        if proc and getattr(proc, '_job_terminated', False):
                            job._set_terminated(exitcode)
                        else:
                            self.on_job_process_lost(
                                job, acked_by_gone, exitcode,
                            )
                else:
                    # started writing to
                    write_to = job._write_to
                    # was scheduled to write to
                    sched_for = job._scheduled_for

                    if write_to and not write_to._is_alive():
                        self.on_job_process_down(job, write_to.pid)
                    elif sched_for and not sched_for._is_alive():
                        self.on_job_process_down(job, sched_for.pid)

            for worker in values(cleaned):
                if self.on_process_down:
                    if not shutdown:
                        self._process_cleanup_queues(worker)
                    self.on_process_down(worker)
            return list(exitcodes.values())
        return []

    def on_partial_read(self, job, worker):
        pass

    def _process_cleanup_queues(self, worker):
        pass

    def on_job_process_down(self, job, pid_gone):
        pass

    def on_job_process_lost(self, job, pid, exitcode):
        job._worker_lost = (monotonic(), exitcode)

    def mark_as_worker_lost(self, job, exitcode):
        try:
            raise WorkerLostError(
                'Worker exited prematurely: {0}.'.format(
                    human_status(exitcode)),
            )
        except WorkerLostError:
            job._set(None, (False, ExceptionInfo()))
        else:  # pragma: no cover
            pass

    def __enter__(self):
        return self

    def __exit__(self, *exc_info):
        return self.terminate()

    def on_grow(self, n):
        pass

    def on_shrink(self, n):
        pass

    def shrink(self, n=1):
        for i, worker in enumerate(self._iterinactive()):
            self._processes -= 1
            if self._putlock:
                self._putlock.shrink()
            worker.terminate_controlled()
            self.on_shrink(1)
            if i >= n - 1:
                break
        else:
            raise ValueError("Can't shrink pool. All processes busy!")

    def grow(self, n=1):
        for i in range(n):
            self._processes += 1
            if self._putlock:
                self._putlock.grow()
        self.on_grow(n)

    def _iterinactive(self):
        for worker in self._pool:
            if not self._worker_active(worker):
                yield worker

    def _worker_active(self, worker):
        for job in values(self._cache):
            if worker.pid in job.worker_pids():
                return True
        return False

    def _repopulate_pool(self, exitcodes):
        """Bring the number of pool processes up to the specified number,
        for use after reaping workers which have exited.
        """
        for i in range(self._processes - len(self._pool)):
            if self._state != RUN:
                return
            try:
                if exitcodes and exitcodes[i] not in (EX_OK, EX_RECYCLE):
                    self.restart_state.step()
            except IndexError:
                self.restart_state.step()
            self._create_worker_process(self._avail_index())
            debug('added worker')

    def _avail_index(self):
        assert len(self._pool) < self._processes
        indices = set(p.index for p in self._pool)
        return next(i for i in range(self._processes) if i not in indices)

    def did_start_ok(self):
        return not self._join_exited_workers()

    def _maintain_pool(self):
        """"Clean up any exited workers and start replacements for them.
        """
        joined = self._join_exited_workers()
        self._repopulate_pool(joined)
        for i in range(len(joined)):
            if self._putlock is not None:
                self._putlock.release()

    def maintain_pool(self):
        if self._worker_handler._state == RUN and self._state == RUN:
            try:
                self._maintain_pool()
            except RestartFreqExceeded:
                self.close()
                self.join()
                raise
            except OSError as exc:
                if get_errno(exc) == errno.ENOMEM:
                    reraise(MemoryError,
                            MemoryError(str(exc)),
                            sys.exc_info()[2])
                raise

    def _setup_queues(self):
        self._inqueue = self._ctx.SimpleQueue()
        self._outqueue = self._ctx.SimpleQueue()
        self._quick_put = self._inqueue._writer.send
        self._quick_get = self._outqueue._reader.recv

        def _poll_result(timeout):
            if self._outqueue._reader.poll(timeout):
                return True, self._quick_get()
            return False, None
        self._poll_result = _poll_result

    def _start_timeout_handler(self):
        # ensure more than one thread does not start the timeout handler
        # thread at once.
        if self.threads and self._timeout_handler is not None:
            with self._timeout_handler_mutex:
                if not self._timeout_handler_started:
                    self._timeout_handler_started = True
                    self._timeout_handler.start()

    def apply(self, func, args=(), kwds={}):
        '''
        Equivalent of `func(*args, **kwargs)`.
        '''
        if self._state == RUN:
            return self.apply_async(func, args, kwds).get()

    def starmap(self, func, iterable, chunksize=None):
        '''
        Like `map()` method but the elements of the `iterable` are expected to
        be iterables as well and will be unpacked as arguments. Hence
        `func` and (a, b) becomes func(a, b).
        '''
        if self._state == RUN:
            return self._map_async(func, iterable,
                                   starmapstar, chunksize).get()

    def starmap_async(self, func, iterable, chunksize=None,
                      callback=None, error_callback=None):
        '''
        Asynchronous version of `starmap()` method.
        '''
        if self._state == RUN:
            return self._map_async(func, iterable, starmapstar, chunksize,
                                   callback, error_callback)

    def map(self, func, iterable, chunksize=None):
        '''
        Apply `func` to each element in `iterable`, collecting the results
        in a list that is returned.
        '''
        if self._state == RUN:
            return self.map_async(func, iterable, chunksize).get()

    def imap(self, func, iterable, chunksize=1, lost_worker_timeout=None):
        '''
        Equivalent of `map()` -- can be MUCH slower than `Pool.map()`.
        '''
        if self._state != RUN:
            return
        lost_worker_timeout = lost_worker_timeout or self.lost_worker_timeout
        if chunksize == 1:
            result = IMapIterator(self._cache,
                                  lost_worker_timeout=lost_worker_timeout)
            self._taskqueue.put((
                ((TASK, (result._job, i, func, (x,), {}))
                 for i, x in enumerate(iterable)),
                result._set_length,
            ))
            return result
        else:
            assert chunksize > 1
            task_batches = Pool._get_tasks(func, iterable, chunksize)
            result = IMapIterator(self._cache,
                                  lost_worker_timeout=lost_worker_timeout)
            self._taskqueue.put((
                ((TASK, (result._job, i, mapstar, (x,), {}))
                 for i, x in enumerate(task_batches)),
                result._set_length,
            ))
            return (item for chunk in result for item in chunk)

    def imap_unordered(self, func, iterable, chunksize=1,
                       lost_worker_timeout=None):
        '''
        Like `imap()` method but ordering of results is arbitrary.
        '''
        if self._state != RUN:
            return
        lost_worker_timeout = lost_worker_timeout or self.lost_worker_timeout
        if chunksize == 1:
            result = IMapUnorderedIterator(
                self._cache, lost_worker_timeout=lost_worker_timeout,
            )
            self._taskqueue.put((
                ((TASK, (result._job, i, func, (x,), {}))
                 for i, x in enumerate(iterable)),
                result._set_length,
            ))
            return result
        else:
            assert chunksize > 1
            task_batches = Pool._get_tasks(func, iterable, chunksize)
            result = IMapUnorderedIterator(
                self._cache, lost_worker_timeout=lost_worker_timeout,
            )
            self._taskqueue.put((
                ((TASK, (result._job, i, mapstar, (x,), {}))
                 for i, x in enumerate(task_batches)),
                result._set_length,
            ))
            return (item for chunk in result for item in chunk)

    def apply_async(self, func, args=(), kwds={},
                    callback=None, error_callback=None, accept_callback=None,
                    timeout_callback=None, waitforslot=None,
                    soft_timeout=None, timeout=None, lost_worker_timeout=None,
                    callbacks_propagate=(),
                    correlation_id=None):
        '''
        Asynchronous equivalent of `apply()` method.

        Callback is called when the functions return value is ready.
        The accept callback is called when the job is accepted to be executed.

        Simplified the flow is like this:

            >>> def apply_async(func, args, kwds, callback, accept_callback):
            ...     if accept_callback:
            ...         accept_callback()
            ...     retval = func(*args, **kwds)
            ...     if callback:
            ...         callback(retval)

        '''
        if self._state != RUN:
            return
        soft_timeout = soft_timeout or self.soft_timeout
        timeout = timeout or self.timeout
        lost_worker_timeout = lost_worker_timeout or self.lost_worker_timeout
        if soft_timeout and SIG_SOFT_TIMEOUT is None:
            warnings.warn(UserWarning(
                "Soft timeouts are not supported: "
                "on this platform: It does not have the SIGUSR1 signal.",
            ))
            soft_timeout = None
        if self._state == RUN:
            waitforslot = self.putlocks if waitforslot is None else waitforslot
            if waitforslot and self._putlock is not None:
                self._putlock.acquire()
            result = ApplyResult(
                self._cache, callback, accept_callback, timeout_callback,
                error_callback, soft_timeout, timeout, lost_worker_timeout,
                on_timeout_set=self.on_timeout_set,
                on_timeout_cancel=self.on_timeout_cancel,
                callbacks_propagate=callbacks_propagate,
                send_ack=self.send_ack if self.synack else None,
                correlation_id=correlation_id,
            )
            if timeout or soft_timeout:
                # start the timeout handler thread when required.
                self._start_timeout_handler()
            if self.threads:
                self._taskqueue.put(([(TASK, (result._job, None,
                                    func, args, kwds))], None))
            else:
                self._quick_put((TASK, (result._job, None, func, args, kwds)))
            return result

    def send_ack(self, response, job, i, fd):
        pass

    def terminate_job(self, pid, sig=None):
        proc, _ = self._process_by_pid(pid)
        if proc is not None:
            try:
                _kill(pid, sig or TERM_SIGNAL)
            except OSError as exc:
                if get_errno(exc) != errno.ESRCH:
                    raise
            else:
                proc._controlled_termination = True
                proc._job_terminated = True

    def map_async(self, func, iterable, chunksize=None,
                  callback=None, error_callback=None):
        '''
        Asynchronous equivalent of `map()` method.
        '''
        return self._map_async(
            func, iterable, mapstar, chunksize, callback, error_callback,
        )

    def _map_async(self, func, iterable, mapper, chunksize=None,
                   callback=None, error_callback=None):
        '''
        Helper function to implement map, starmap and their async counterparts.
        '''
        if self._state != RUN:
            return
        if not hasattr(iterable, '__len__'):
            iterable = list(iterable)

        if chunksize is None:
            chunksize, extra = divmod(len(iterable), len(self._pool) * 4)
            if extra:
                chunksize += 1
        if len(iterable) == 0:
            chunksize = 0

        task_batches = Pool._get_tasks(func, iterable, chunksize)
        result = MapResult(self._cache, chunksize, len(iterable), callback,
                           error_callback=error_callback)
        self._taskqueue.put((((TASK, (result._job, i, mapper, (x,), {}))
                              for i, x in enumerate(task_batches)), None))
        return result

    @staticmethod
    def _get_tasks(func, it, size):
        it = iter(it)
        while 1:
            x = tuple(itertools.islice(it, size))
            if not x:
                return
            yield (func, x)

    def __reduce__(self):
        raise NotImplementedError(
            'pool objects cannot be passed between processes or pickled',
        )

    def close(self):
        debug('closing pool')
        if self._state == RUN:
            self._state = CLOSE
            if self._putlock:
                self._putlock.clear()
            self._worker_handler.close()
            self._taskqueue.put(None)
            stop_if_not_current(self._worker_handler)

    def terminate(self):
        debug('terminating pool')
        self._state = TERMINATE
        self._worker_handler.terminate()
        self._terminate()

    @staticmethod
    def _stop_task_handler(task_handler):
        stop_if_not_current(task_handler)

    def join(self):
        assert self._state in (CLOSE, TERMINATE)
        debug('joining worker handler')
        stop_if_not_current(self._worker_handler)
        debug('joining task handler')
        self._stop_task_handler(self._task_handler)
        debug('joining result handler')
        stop_if_not_current(self._result_handler)
        debug('result handler joined')
        for i, p in enumerate(self._pool):
            debug('joining worker %s/%s (%r)', i + 1, len(self._pool), p)
            if p._popen is not None:  # process started?
                p.join()
        debug('pool join complete')

    def restart(self):
        for e in values(self._poolctrl):
            e.set()

    @staticmethod
    def _help_stuff_finish(inqueue, task_handler, _pool):
        # task_handler may be blocked trying to put items on inqueue
        debug('removing tasks from inqueue until task handler finished')
        inqueue._rlock.acquire()
        while task_handler.is_alive() and inqueue._reader.poll():
            inqueue._reader.recv()
            time.sleep(0)

    @classmethod
    def _set_result_sentinel(cls, outqueue, pool):
        outqueue.put(None)

    @classmethod
    def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool,
                        worker_handler, task_handler,
                        result_handler, cache, timeout_handler,
                        help_stuff_finish_args):

        # this is guaranteed to only be called once
        debug('finalizing pool')

        worker_handler.terminate()

        task_handler.terminate()
        taskqueue.put(None)                 # sentinel

        debug('helping task handler/workers to finish')
        cls._help_stuff_finish(*help_stuff_finish_args)

        result_handler.terminate()
        cls._set_result_sentinel(outqueue, pool)

        if timeout_handler is not None:
            timeout_handler.terminate()

        # Terminate workers which haven't already finished
        if pool and hasattr(pool[0], 'terminate'):
            debug('terminating workers')
            for p in pool:
                if p._is_alive():
                    p.terminate()

        debug('joining task handler')
        cls._stop_task_handler(task_handler)

        debug('joining result handler')
        result_handler.stop()

        if timeout_handler is not None:
            debug('joining timeout handler')
            timeout_handler.stop(TIMEOUT_MAX)

        if pool and hasattr(pool[0], 'terminate'):
            debug('joining pool workers')
            for p in pool:
                if p.is_alive():
                    # worker has not yet exited
                    debug('cleaning up worker %d', p.pid)
                    if p._popen is not None:
                        p.join()
            debug('pool workers joined')

    @property
    def process_sentinels(self):
        return [w._popen.sentinel for w in self._pool]

#
# Class whose instances are returned by `Pool.apply_async()`
#


class ApplyResult(object):
    _worker_lost = None
    _write_to = None
    _scheduled_for = None

    def __init__(self, cache, callback, accept_callback=None,
                 timeout_callback=None, error_callback=None, soft_timeout=None,
                 timeout=None, lost_worker_timeout=LOST_WORKER_TIMEOUT,
                 on_timeout_set=None, on_timeout_cancel=None,
                 callbacks_propagate=(), send_ack=None,
                 correlation_id=None):
        self.correlation_id = correlation_id
        self._mutex = Lock()
        self._event = threading.Event()
        self._job = next(job_counter)
        self._cache = cache
        self._callback = callback
        self._accept_callback = accept_callback
        self._error_callback = error_callback
        self._timeout_callback = timeout_callback
        self._timeout = timeout
        self._soft_timeout = soft_timeout
        self._lost_worker_timeout = lost_worker_timeout
        self._on_timeout_set = on_timeout_set
        self._on_timeout_cancel = on_timeout_cancel
        self._callbacks_propagate = callbacks_propagate or ()
        self._send_ack = send_ack

        self._accepted = False
        self._cancelled = False
        self._worker_pid = None
        self._time_accepted = None
        self._terminated = None
        cache[self._job] = self

    def __repr__(self):
        return '<%s: {id} ack:{ack} ready:{ready}>'.format(
            self.__class__.__name__,
            id=self._job, ack=self._accepted, ready=self.ready(),
        )

    def ready(self):
        return self._event.isSet()

    def accepted(self):
        return self._accepted

    def successful(self):
        assert self.ready()
        return self._success

    def _cancel(self):
        """Only works if synack is used."""
        self._cancelled = True

    def discard(self):
        self._cache.pop(self._job, None)

    def terminate(self, signum):
        self._terminated = signum

    def _set_terminated(self, signum=None):
        try:
            raise Terminated(-(signum or 0))
        except Terminated:
            self._set(None, (False, ExceptionInfo()))

    def worker_pids(self):
        return [self._worker_pid] if self._worker_pid else []

    def wait(self, timeout=None):
        self._event.wait(timeout)

    def get(self, timeout=None):
        self.wait(timeout)
        if not self.ready():
            raise TimeoutError
        if self._success:
            return self._value
        else:
            raise self._value.exception

    def safe_apply_callback(self, fun, *args, **kwargs):
        if fun:
            try:
                fun(*args, **kwargs)
            except self._callbacks_propagate:
                raise
            except Exception as exc:
                error('Pool callback raised exception: %r', exc,
                      exc_info=1)

    def handle_timeout(self, soft=False):
        if self._timeout_callback is not None:
            self.safe_apply_callback(
                self._timeout_callback, soft=soft,
                timeout=self._soft_timeout if soft else self._timeout,
            )

    def _set(self, i, obj):
        with self._mutex:
            if self._on_timeout_cancel:
                self._on_timeout_cancel(self)
            self._success, self._value = obj
            self._event.set()
            if self._accepted:
                # if not accepted yet, then the set message
                # was received before the ack, which means
                # the ack will remove the entry.
                self._cache.pop(self._job, None)

            # apply callbacks last
            if self._callback and self._success:
                self.safe_apply_callback(
                    self._callback, self._value)
            if (self._value is not None and
                    self._error_callback and not self._success):
                self.safe_apply_callback(
                    self._error_callback, self._value)

    def _ack(self, i, time_accepted, pid, synqW_fd):
        with self._mutex:
            if self._cancelled and self._send_ack:
                self._accepted = True
                if synqW_fd:
                    return self._send_ack(NACK, pid, self._job, synqW_fd)
                return
            self._accepted = True
            self._time_accepted = time_accepted
            self._worker_pid = pid
            if self.ready():
                # ack received after set()
                self._cache.pop(self._job, None)
            if self._on_timeout_set:
                self._on_timeout_set(self, self._soft_timeout, self._timeout)
            response = ACK
            if self._accept_callback:
                try:
                    self._accept_callback(pid, time_accepted)
                except self._propagate_errors:
                    response = NACK
                    raise
                except Exception:
                    response = NACK
                    # ignore other errors
                finally:
                    if self._send_ack and synqW_fd:
                        return self._send_ack(
                            response, pid, self._job, synqW_fd
                        )
            if self._send_ack and synqW_fd:
                self._send_ack(response, pid, self._job, synqW_fd)

#
# Class whose instances are returned by `Pool.map_async()`
#


class MapResult(ApplyResult):

    def __init__(self, cache, chunksize, length, callback, error_callback):
        ApplyResult.__init__(
            self, cache, callback, error_callback=error_callback,
        )
        self._success = True
        self._length = length
        self._value = [None] * length
        self._accepted = [False] * length
        self._worker_pid = [None] * length
        self._time_accepted = [None] * length
        self._chunksize = chunksize
        if chunksize <= 0:
            self._number_left = 0
            self._event.set()
            del cache[self._job]
        else:
            self._number_left = length // chunksize + bool(length % chunksize)

    def _set(self, i, success_result):
        success, result = success_result
        if success:
            self._value[i * self._chunksize:(i + 1) * self._chunksize] = result
            self._number_left -= 1
            if self._number_left == 0:
                if self._callback:
                    self._callback(self._value)
                if self._accepted:
                    self._cache.pop(self._job, None)
                self._event.set()
        else:
            self._success = False
            self._value = result
            if self._error_callback:
                self._error_callback(self._value)
            if self._accepted:
                self._cache.pop(self._job, None)
            self._event.set()

    def _ack(self, i, time_accepted, pid, *args):
        start = i * self._chunksize
        stop = min((i + 1) * self._chunksize, self._length)
        for j in range(start, stop):
            self._accepted[j] = True
            self._worker_pid[j] = pid
            self._time_accepted[j] = time_accepted
        if self.ready():
            self._cache.pop(self._job, None)

    def accepted(self):
        return all(self._accepted)

    def worker_pids(self):
        return [pid for pid in self._worker_pid if pid]

#
# Class whose instances are returned by `Pool.imap()`
#


class IMapIterator(object):
    _worker_lost = None

    def __init__(self, cache, lost_worker_timeout=LOST_WORKER_TIMEOUT):
        self._cond = threading.Condition(threading.Lock())
        self._job = next(job_counter)
        self._cache = cache
        self._items = deque()
        self._index = 0
        self._length = None
        self._ready = False
        self._unsorted = {}
        self._worker_pids = []
        self._lost_worker_timeout = lost_worker_timeout
        cache[self._job] = self

    def __iter__(self):
        return self

    def next(self, timeout=None):
        with self._cond:
            try:
                item = self._items.popleft()
            except IndexError:
                if self._index == self._length:
                    self._ready = True
                    raise StopIteration
                self._cond.wait(timeout)
                try:
                    item = self._items.popleft()
                except IndexError:
                    if self._index == self._length:
                        self._ready = True
                        raise StopIteration
                    raise TimeoutError

        success, value = item
        if success:
            return value
        raise Exception(value)

    __next__ = next                    # XXX

    def _set(self, i, obj):
        with self._cond:
            if self._index == i:
                self._items.append(obj)
                self._index += 1
                while self._index in self._unsorted:
                    obj = self._unsorted.pop(self._index)
                    self._items.append(obj)
                    self._index += 1
                self._cond.notify()
            else:
                self._unsorted[i] = obj

            if self._index == self._length:
                self._ready = True
                del self._cache[self._job]

    def _set_length(self, length):
        with self._cond:
            self._length = length
            if self._index == self._length:
                self._ready = True
                self._cond.notify()
                del self._cache[self._job]

    def _ack(self, i, time_accepted, pid, *args):
        self._worker_pids.append(pid)

    def ready(self):
        return self._ready

    def worker_pids(self):
        return self._worker_pids

#
# Class whose instances are returned by `Pool.imap_unordered()`
#


class IMapUnorderedIterator(IMapIterator):

    def _set(self, i, obj):
        with self._cond:
            self._items.append(obj)
            self._index += 1
            self._cond.notify()
            if self._index == self._length:
                self._ready = True
                del self._cache[self._job]

#
#
#


class ThreadPool(Pool):

    from .dummy import Process as DummyProcess
    Process = DummyProcess

    def __init__(self, processes=None, initializer=None, initargs=()):
        Pool.__init__(self, processes, initializer, initargs)

    def _setup_queues(self):
        self._inqueue = Queue()
        self._outqueue = Queue()
        self._quick_put = self._inqueue.put
        self._quick_get = self._outqueue.get

        def _poll_result(timeout):
            try:
                return True, self._quick_get(timeout=timeout)
            except Empty:
                return False, None
        self._poll_result = _poll_result

    @staticmethod
    def _help_stuff_finish(inqueue, task_handler, pool):
        # put sentinels at head of inqueue to make workers finish
        with inqueue.not_empty:
            inqueue.queue.clear()
            inqueue.queue.extend([None] * len(pool))
            inqueue.not_empty.notify_all()