[英]python generators for concurrency
我正在關注 Python 大師 David Beazley 的幻燈片。 它指出“生成器也用於並發。這是一個例子:
from collections import deque
def countdown(n):
while n > 0:
print("T-minus", n)
yield
n -=1
def countup(n):
x = 0
while x > n:
print("Up we go", x)
yield
x +=1
# instantiate some tasks in a queue
tasks = deque([countdown(10),
countdown(5),
countup(20)
])
# run a little scheduler
while tasks:
t = tasks.pop() # get a task
try:
next(t) # run it until it yields
tasks.appendleft(t) # reschedule
except StopIteration:
pass
這是輸出:
T-minus 5
T-minus 10
T-minus 4
T-minus 9
T-minus 3
T-minus 8
T-minus 2
T-minus 7
T-minus 1
T-minus 6
T-minus 5
T-minus 4
T-minus 3
T-minus 2
T-minus 1
問題是生成器是如何引入並發性的,它是如何表現出來的?
這段代碼實現了“綠色線程”、協作、用戶空間(相對於搶占式、內核)線程的概念。
“線程”是生成器,每個函數都包含yeild
或yield from
。 顯然,調度程序存在於if __name__ == '__main__':
位中。
因此,假設我們沒有生成器,而是常規列表,並且每個列表中都有一個函數序列。
def doThis(): pass
def sayThis(): pass
def doThat(): pass
...
myThread = [doThis, doThat, doAnother]
yourThread = [sayThis, sayThat, sayAnother]
我們可以按順序運行所有函數:
for thread in [myThread, yourThread]:
for stmt in thread:
stmt()
或者我們可以按其他順序進行:
for myStmt, yourStmt in zip(myThread, yourThread):
myStmt()
yourStmt()
在第一個“調度器”中,我們耗盡了第一個線程,然后再進行第二個線程。 在第二個調度程序中,我們將兩個線程中的語句交織在一起,首先是我的,然后是你的,然后是我的。
這是因為我們在耗盡那些線程之前在多個“線程”中交錯“語句”,我們可以說第二個調度程序提供並發性。
請注意,並發並不一定意味着並行。 這不是同時執行,只是重疊。
這是一個澄清的例子:
from collections import deque
def coro1():
for i in range(1, 10):
yield i
def coro2():
for i in range(1, 10):
yield i*10
print('Async behaviour'.center(60, '#'))
tasks = deque()
tasks.extend([coro1(), coro2()])
while tasks:
task = tasks.popleft() # select and remove a task (coro1/coro2).
try:
print(next(task))
tasks.append(task) # add the removed task (coro1/coro2) for permutation.
except StopIteration:
pass
出去:
######################Async behaviour#######################
1
10
2
20
3
30
4
40
5
50
6
60
7
70
8
80
9
90
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.