python - 一个干净的 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。相反,一种使函数调用线程化的更简洁的方法
解决方案
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))
推荐阅读
- javascript - 在 hotreload 之后反应连接调用,是 webpack 配置吗?
- java - 禁用 XML 中的自动 & 符号转义?
- python - 根据另一个日期列将日期列添加到数据框
- spinnaker - 大三角帆中自定义工件的用途是什么,它总是给出错误 - 自定义引用被传递到云平台以处理或处理 500
- ruby - 如何在ruby中迭代完整的哈希数组-仅检索第一个
- swagger - Swagger 识别 REST API 中的稀有端点
- android - CameraX:如何显示 16:9 比例预览?
- java - 如何更改从 JSON Schema 生成的 POJO 的格式?
- javascript - 如何在 Chrome 开发者工具中禁用加载特定脚本
- python - 具有十进制比较和输出的 Python 脚本