我开始学习异步代码,我已经阅读了很多内容,但我似乎无法找到非常简单的示例来自己尝试并更好地理解它。
我想编写一个简单的Python(最好是3.5)程序来执行以下操作:
1)调用等待几秒钟的虚拟异步函数dummy()
并返回一些东西
2)继续做事,直到dummy()
返回一些东西为止
3)从dummy()
检索返回值并输入变量
4)继续做事
我该怎么做?
修改
很抱歉,如果这不清楚,但我知道如何使用线程来做到这一点。我的目标是使用 async-await 语句和 asyncio 模块执行此操作。
答案 0 :(得分:3)
为了尝试回答您的问题,我已经修改了asyncio文档中的一个示例,以包含更多您要求的内容。 https://docs.python.org/3/library/asyncio-task.html
import asyncio
result2 = 0
async def compute(x, y):
print("Compute %s + %s ..." % (x, y))
await asyncio.sleep(1.0)
result2 = x*y
return x + y
async def print_sum(x, y):
result = await compute(x, y)
print("%s + %s = %s" % (x, y, result))
async def dosomethingelse():
print("I've got a lovely bunch of coconuts")
loop = asyncio.get_event_loop()
tasks = [print_sum(1, 2),
dosomethingelse(),
compute(2, 4)
]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
print(result2)
如果你运行上面的内容,你应该看到dosomethingelse运行,而compute正在等待。
我发现异步编程真的难以理解。但我认为asyncio实际上比线程或多处理要简单得多,因为所有内容都运行在相同的内存空间中(并且使用这样的简单协程),程序流程是完全顺序的。第一个任务一直运行,直到它到达await
,然后下一个任务有机会,依此类推。我强烈建议您阅读模块文档,这非常好,并尝试编写一些示例来探索每个主题。从协程开始,然后链接,然后回调。
yield from
语法是因为我当时使用的是较旧版本的python 3。
我不记得我正在阅读的教程,但这是我写的第一个asyncio测试之一。
import asyncio
@asyncio.coroutine
def my_coroutine(task_name, seconds_to_sleep=3):
print("{0} sleeping for: {1} seconds".format(task_name, seconds_to_sleep))
yield from asyncio.sleep(seconds_to_sleep)
print("{0} is finished".format(task_name))
loop = asyncio.get_event_loop()
tasks = [my_coroutine("task1", 4),
my_coroutine("task2", 2),
my_coroutine("task3", 10)]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
答案 1 :(得分:1)
坚持你的问题(因为还有其他方法可以实现你想要的),一个简单的答案如下:
import threading
import time
results = []
def dummy():
time.sleep(2)
results.append("This function result!")
return
t = threading.Thread(target=dummy)
t.start()
while t.isAlive():
print('Something')
print(results) # ['This function result!']