【问题标题】:Asyncio and thread in PythonPython中的异步和线程
【发布时间】:2019-09-25 02:42:55
【问题描述】:

我想在 python 中使用异步,如 c# 或 javascript。例如,我希望我的程序在发送请求时不要阻止下一个代码或应用程序中的按钮。我为此编写了一些代码。但是我不知道这种用法是否是真还是假。我看不懂asyncio

import asyncio
import threading
import time

async def waitForMe(name):
    for i in range(5):
        await asyncio.sleep(1)
        print(name)

async def main():
    task1 = asyncio.create_task(waitForMe("task1"))
    task2 = asyncio.create_task(waitForMe("task2"))
    task3 = asyncio.create_task(waitForMe("task3"))
    await task1
    await task2
    await task3

def mfunction():   
    asyncio.run(main())
t1=threading.Thread(target=mfunction)
t1.start()
for i in range(3):
    time.sleep(1)
    print("main")

【问题讨论】:

  • 你到底在问什么?
  • 请参阅 [this 优秀的 asyncio 介绍](realpython.com/async-io-python)。
  • 所以如果我在这里不使用线程,"print(main)" 等待结束任务。不是吗?我不想要这个
  • promise1.then(onfullfilledfunction=function(value) { console.log(value); }).catch(onrejected=function(error){ console.log(error) }); setInterval(function(){ console.log("not block") },1000);我可以说我在 python 中搜索相同的代码

标签: python multithreading python-asyncio


【解决方案1】:

我真的推荐 this 优秀的 asyncio 演练,它应该可以回答您的大部分问题。

根据您的代码引用上述文章:

[...] 异步 IO 是一种单线程、单进程设计:它使用协作多任务处理,这个术语 [...] 尽管在单个进程中使用单个线程,但它给人一种并发的感觉。

如果您不希望您的程序在处理(IO)请求时阻塞(如您的问题中所述),并发性就足够了(并且您不需要(多)线程)!

并发 [...] 表明多个任务能够以重叠方式运行。

我将重复上述文章中的确切示例,其结构与您的示例相似:

#!/usr/bin/env python3
# countasync.py

import asyncio

async def count():
    print("One")
    await asyncio.sleep(1)
    print("Two")

async def main():
    await asyncio.gather(count(), count(), count())

if __name__ == "__main__":
    import time
    s = time.perf_counter()
    asyncio.run(main())
    elapsed = time.perf_counter() - s
    print(f"{__file__} executed in {elapsed:0.2f} seconds.")

运行如下:

$ python3 countasync.py
One
One
One
Two
Two
Two
countasync.py executed in 1.01 seconds.

请注意,此示例使用asyncio.gather 以非阻塞方式启动三个count() 进程。将三个await count() 声明一个接一个是行不通的。

据我所知,这正是您正在寻找的。如图所示,您不需要threading 来实现此目的。

【讨论】:

    猜你喜欢
    • 2018-03-02
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 2019-09-13
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多