首页 > 解决方案 > 一个干净的 API,用于在 python 中进行函数调用线程化

问题描述

我想在线程中调用一个函数。使用常规 API 调用它看起来像:

from threading import Thread
import numpy as np
a = np.random.rand(int(1e8),1)

Thread(target=np.savez_compressed, args=('/tmp/values.a', dict(a=a))).start()

我想知道是否有一个 pythonic 是用更干净的 API 进行这个线程调用,而不定义一个特定于np.savez_compressed.

例如(伪代码)风格的东西:

@make_threaded
np.savez_compressed('/tmp/values.a', dict(a=a))

不幸的是,装饰器只能应用于函数定义,所以上面的伪代码是不合法的。

编辑:我不是专门寻找装饰器 API。相反,一种使函数调用线程化的更简洁的方法

标签: pythonpython-3.xpython-multithreading

解决方案


The concurrent.futures module provides a more high-level API for using threads or processes for individual operations.

from concurrent.futures import ThreadPoolExecutor

executor = ThreadPoolExecutor()
executor.submit(np.savez_compressed, '/tmp/values.a', dict(a=a))

If you don't want the entire Executor API, you can define your own helper to run a function in a thread.

def threaded(call, *args, **kwargs):
    """Execute ``call(*args, **kwargs)`` in a thread"""
    thread = threading.Thread(target=call, args=args, kwargs=kwargs)
    thread.start()
    return thread

threaded(np.savez_compressed, '/tmp/values.a', dict(a=a))

推荐阅读