根本没有正确的选择,我们只有靠奋斗来使当初的选择显得正确。

—— 一个有思考的程序员

【Python协程】

标签:
coroutine
asyncio
async
await
asyncio.create_task()
asyncio.gather()
协程的并发优于多线程的并发是:协程有极高的执行效率,不需要考虑线程间同步、死锁等问题
1.普通函数
import time

def task1():
    for i in range(10):
        print(i)
        time.sleep(2)

def task2():
    chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
    for i in chars:
        print(i)
        time.sleep(2)

start = time.time()
task1()
task2()
end = time.time()
print(f'运行完毕,耗时: {end-start}')
  
运行结果为:
0
1
2
3
4
5
6
7
8
9
a
b
c
d
e
f
g
h
i
j
运行完毕,耗时: 40.01112508773804
2.协程并发
import asyncio

async def coroutine_task1():
    for i in range(10):
        print(i)
        await asyncio.sleep(2)

async def coroutine_task2():
    chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
    for i in chars:
        print(i)
        await asyncio.sleep(2)
'''
task1 = asyncio.create_task(coroutine_task1())
task2 = asyncio.create_task(coroutine_task2())

start = time.time()
await task1
await task2
end = time.time()
print(f'运行完毕,耗时: {end-start}')
'''
start = time.time()
await asyncio.gather(
    coroutine_task1(),
    coroutine_task2(),
)
end = time.time()
print(f'运行完毕,耗时: {end-start}')
  
运行结果为:
0
a
1
b
2
c
3
d
4
e
5
f
6
g
7
h
8
i
9
j
运行完毕,耗时: 20.0049045085907