threads.py 文件源码

python
阅读 30 收藏 0 点赞 0 评论 0

项目:asyncio_extras 作者: agronholm 项目源码 文件源码
def threadpool(arg: Union[Executor, Callable] = None):
    """
    Return a decorator/asynchronous context manager that guarantees that the wrapped function or
    ``with`` block is run in the given executor.

    If no executor is given, the current event loop's default executor is used.
    Otherwise, the executor must be a PEP 3148 compliant thread pool executor.

    Callables wrapped with this must be used with ``await`` when called in the event loop thread.
    They can also be called in worker threads, just by omitting the ``await``.

    Example use as a decorator::

        @threadpool
        def this_runs_in_threadpool():
           return do_something_cpu_intensive()

        async def request_handler():
            result = await this_runs_in_threadpool()

    Example use as an asynchronous context manager::

        async def request_handler(in_url, out_url):
            page = await http_fetch(in_url)

            async with threadpool():
                data = transform_page(page)

            await http_post(out_url, page)

    :param arg: either a callable (when used as a decorator) or an executor in which to run the
        wrapped callable or the ``with`` block (when used as a context manager)

    """
    if callable(arg):
        # When used like @threadpool
        return _ThreadSwitcher(None)(arg)
    else:
        # When used like @threadpool(...) or async with threadpool(...)
        return _ThreadSwitcher(arg)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号