Yuv*_*mon 5 python python-multithreading python-3.x
我想在线程中调用一个函数。使用传统 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()
Run Code Online (Sandbox Code Playgroud)
我想知道是否有一个 pythonic 是使用更干净的 API 进行这个线程调用,而不定义一个特定于np.savez_compressed.
例如(伪代码)风格的东西:
@make_threaded
np.savez_compressed('/tmp/values.a', dict(a=a))
Run Code Online (Sandbox Code Playgroud)
不幸的是,装饰器只能应用于函数定义,所以上面的伪代码是不合法的。
编辑:我不是专门寻找装饰器 API。相反,一种使函数调用线程化的更简洁的方法
该concurrent.futures模块提供了更高级的 API,用于使用线程或进程进行单独的操作。
from concurrent.futures import ThreadPoolExecutor
executor = ThreadPoolExecutor()
executor.submit(np.savez_compressed, '/tmp/values.a', dict(a=a))
Run Code Online (Sandbox Code Playgroud)
如果您不需要整个 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))
Run Code Online (Sandbox Code Playgroud)