天天看點

coroutine 協程

Coroutines are computer-program components that generalize subroutines for non-preemptive multitasking, by allowing multiple entry points for suspending and resuming execution at certain locations. Coroutines are well-suited for implementing familiar program components such as cooperative tasks, exceptions, event loops, iterators, infinite lists and pipes. The async def type of coroutine was added in Python 3.5, and is recommended if there is no need to support older Python versions.

由于GIL的存在,導緻Python多線程性能甚至比單線程更糟。

GIL: 全局解釋器鎖(英語:Global Interpreter Lock,縮寫GIL),是計算機程式設計語言解釋器用于同步線程的一種機制,它使得任何時刻僅有一個線程在執行。[1]即便在多核心處理器上,使用 GIL 的解釋器也隻允許同一時間執行一個線程。

于是出現了協程(Coroutine)這麼個東西。

協程/微線程/纖程/Coroutine作用是在執行函數A時,可以随時中斷,去執行函數B,然後中斷繼續執行函數A(可以自由切換)。但這一過程并不是函數調用(沒有調用語句),這一整個過程看似像多線程,然而協程隻有一個線程執行。

import asyncio

async def compute(x, y):
    print("Compute %s + %s ..." % (x, y))
    await asyncio.sleep(1.0)
    return x + y

async def print_sum(x, y):
    result = await compute(x, y)
    print("%s + %s = %s" % (x, y, result))

loop = asyncio.get_event_loop()
loop.run_until_complete(print_sum(1, 2))
loop.close()           

複制

Compute 1 + 2 ...
1 + 2 = 3
[Finished in 1.2s]           

複制

coroutine 協程
import asyncio

async def factorial(name, number):
    f = 1
    for i in range(2, number+1):
        print("Task %s: Compute factorial(%s)..." % (name, i))
        await asyncio.sleep(1)
        f *= i
    print("Task %s: factorial(%s) = %s" % (name, number, f))

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(
    factorial("A", 2),
    factorial("B", 3),
    factorial("C", 4),
))
loop.close()           

複制

Task B: Compute factorial(2)...
Task A: Compute factorial(2)...
Task C: Compute factorial(2)...
Task B: Compute factorial(3)...
Task A: factorial(2) = 2
Task C: Compute factorial(3)...
Task B: factorial(3) = 6
Task C: Compute factorial(4)...
Task C: factorial(4) = 24
[Finished in 3.2s]           

複制

https://docs.python.org/zh-cn/3/library/asyncio-task.html

https://juejin.im/post/5c13245ee51d455fa5451f33