一个干净的 API 用于在 python 中进行线程化的函数调用

A clean API for making a function call threaded in 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。相反,一种使函数调用线程化的更简洁的方法

concurrent.futures 模块提供了更高级别的 API 用于使用线程或进程进行单个操作。

from concurrent.futures import ThreadPoolExecutor

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

如果您不想要整个 Executor API,您可以定义自己的帮助程序 运行 线程中的一个函数。

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))

OP 在这里:

我找到的另一个解决方案是将装饰器与装饰器一起使用 "classic" API:

from threading import Thread

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

# 
def call_threaded(fn):        
    def wrapper(*args, **kwargs):
        thread = Thread(target=fn, args=args, kwargs=kwargs)
        thread.start()
        return thread
    return wrapper