简体   繁体   English

Python 中的异步和线程

[英]Asyncio and thread in Python

I want to use async in python like c# or javascript.For example I want my program not to block next codes or maybe buttons in app while sending a request.I wrote some code about that.However I dont know whether this usage is true or false.I can't understand asyncio我想在 python 中使用异步,如 c# 或 javascript。例如,我希望我的程序在发送请求时不阻止下一个代码或应用程序中的按钮。我写了一些关于此的代码是否正确。但是我不知道错误。我无法理解异步

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")

I'd really recommend this excellent asyncio walkthrough, which should answer most of your questions.我真的推荐这个优秀的 asyncio 演练,它应该回答你的大部分问题。

A quote from the mentioned article in the light of your code:根据您的代码引用上述文章:

[...] async IO is a single-threaded, single-process design: it uses cooperative multitasking, a term that [...] gives a feeling of concurrency despite using a single thread in a single process. [...] async IO 是一种单线程、单进程设计:它使用协作多任务处理,尽管在单个进程中使用单个线程,但这个术语 [...] 给人一种并发的感觉。

If you don't want your program to block while processing (IO) requests (as stated in your question), concurrency is sufficient (and you don't need (multi)threading)!如果您不希望您的程序在处理(IO)请求时阻塞(如您的问题所述),并发性就足够了(并且您不需要(多)线程)!

Concurrency [...] suggests that multiple tasks have the ability to run in an overlapping manner.并发 [...] 表明多个任务能够以重叠的方式运行。

I'll repeat the exact example from the mentioned article, which has a similar structure as your example:我将重复上述文章中的确切示例,其结构与您的示例相似:

#!/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.")

This runs as follows:这运行如下:

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

Note that this examples uses asyncio.gather to kick-off the three count() processes in a non-blocking manner.请注意,此示例使用asyncio.gather以非阻塞方式启动三个count()进程。 Putting three await count() statements after one another won't work.一个接一个地放置三个await count()语句是行不通的。

As far as I can see, this is exactly what you are looking for.据我所知,这正是您正在寻找的。 As demonstrated, you don't need threading to achieve this.如图所示,您不需要threading来实现这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM