# Buggy code
def backdown_thread_pool(max_workers=10):
    """Tries to create an executor with max_workers, but will back down ultimately to a single
    thread of the OS decides you can't have more than one.
    """
    try:
        yield ThreadPoolExecutor(max_workers)
    except RuntimeError as e:  # pragma: no cover
        # RuntimeError is thrown if number of threads are limited by OS
        log.debug(repr(e))
        try:
            yield ThreadPoolExecutor(floor(max_workers / 2))
        except RuntimeError as e:
            log.debug(repr(e))
            yield ThreadPoolExecutor(1)


# Traceback (RuntimeError)
error: RuntimeError("generator didn't stop after throw()",)
command: /home/mholekev/miniconda3/bin/conda install --yes numpy scipy matplotlib jupyter git pandas
user_agent: conda/4.4.4 requests/2.18.4 CPython/3.6.3 Linux/2.6.32-696.10.3.el6.x86_64 centos/6.7 glibc/2.12
_messageid: -9223372036842075552
_messagetime: 1514766990662 / 2017-12-31 18:36:30

Traceback (most recent call last):
File "/home/mholekev/miniconda3/lib/python3.6/site-packages/conda/common/io.py", line 399, in backdown_thread_pool
yield ThreadPoolExecutor(max_workers)
File "/home/mholekev/miniconda3/lib/python3.6/site-packages/conda/core/index.py", line 214, in get_reduced_index
new_records = query_all(spec)
File "/home/mholekev/miniconda3/lib/python3.6/site-packages/conda/core/index.py", line 187, in query_all
return tuple(concat(future.result() for future in as_completed(futures)))
File "/home/mholekev/miniconda3/lib/python3.6/site-packages/conda/core/index.py", line 187, in <genexpr>
return tuple(concat(future.result() for future in as_completed(futures)))
File "/home/mholekev/miniconda3/lib/python3.6/concurrent/futures/_base.py", line 217, in as_completed
fs = set(fs)
File "/home/mholekev/miniconda3/lib/python3.6/site-packages/conda/core/index.py", line 186, in <genexpr>
futures = (executor.submit(sd.query, spec) for sd in subdir_datas)
File "/home/mholekev/miniconda3/lib/python3.6/concurrent/futures/thread.py", line 123, in submit
self._adjust_thread_count()
File "/home/mholekev/miniconda3/lib/python3.6/concurrent/futures/thread.py", line 142, in _adjust_thread_count
t.start()
File "/home/mholekev/miniconda3/lib/python3.6/threading.py", line 846, in start
_start_new_thread(self._bootstrap, ())
RuntimeError: can't start new thread

# Fixed code
def backdown_thread_pool(max_workers=10):
    """Tries to create an executor with max_workers, but will back down ultimately to a single
    thread of the OS decides you can't have more than one.
    """
    from concurrent.futures import (
        _base,
    )  # These "_" imports are gross, but I don't think there's an alternative  # NOQA
    from concurrent.futures.thread import _WorkItem

    class CondaThreadPoolExecutor(ThreadPoolExecutor):
        def submit(self, fn, *args, **kwargs):
            with self._shutdown_lock:
                if self._shutdown:
                    raise RuntimeError("cannot schedule new futures after shutdown")

                f = _base.Future()
                w = _WorkItem(f, fn, args, kwargs)

                self._work_queue.put(w)
                try:
                    self._adjust_thread_count()
                except RuntimeError:
                    # RuntimeError: can't start new thread
                    # See https://github.com/conda/conda/issues/6624
                    if len(self._threads) > 0:
                        # It's ok to not be able to start new threads if we already have at least
                        # one thread alive.
                        pass
                    else:
                        raise
                return f

    try:
        yield CondaThreadPoolExecutor(max_workers)
    except RuntimeError as e:  # pragma: no cover
        # RuntimeError is thrown if number of threads are limited by OS
        log.debug(repr(e))
        try:
            yield CondaThreadPoolExecutor(floor(max_workers / 2))
        except RuntimeError as e:
            log.debug(repr(e))
            yield CondaThreadPoolExecutor(1)