【发布时间】:2020-04-21 13:40:03
【问题描述】:
我是python初学者,正在尝试编写一些数据分析程序。程序如下:
import asyncio
import time
class Test:
def __init__(self, task):
self.task = task
time.sleep(5) # here's some other jobs...
print(f'{self.task = }')
async def main():
result = []
tasks = ['task1', 'task2', 'task3', 'task4', 'task5', 'task6', 'task7', 'task8', 'task9']
print(f"started at {time.strftime('%X')}")
# I have a program structure like this, can I use async?
# how to start init tasks at almost the same time?
for task in tasks:
result.append(Test(task))
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
我尝试了其他一些方法,比如多处理,它可以工作,代码如下:
...
def main():
result = []
tasks = ['task1', 'task2', 'task3', 'task4', 'task5', 'task6', 'task7', 'task8', 'task9']
print(f"started at {time.strftime('%X')}")
# I have a program structure like this, can I use async?
# how to start init tasks at the same time?
p = Pool()
result = p.map(operation, [(task,) for task in tasks])
print(f"finished at {time.strftime('%X')}")
...
但我仍然想学习一些“现代方式”来做到这一点。我找到了一个名为“ray”的模块,它是新的。
但是异步可以做到这一点吗?我还在想...
如果有人能给我一些建议,非常感谢。
【问题讨论】: