簡體   English   中英

Python Eventlet不會並發執行

[英]Python Eventlet spawn not executing concurrently

我使用eventlet跟隨兩個版本的代碼。 期望是2個spawn_n調用將同時執行,但事實並非如此。 執行順序發生。

import eventlet
import threading
import datetime
from eventlet.green import urllib2


def hello(name):
    print eventlet.greenthread.getcurrent(), threading.current_thread()
    print datetime.datetime.now()
    print " %s hello !!" % name
    urllib2.urlopen("http://www.google.com/intl/en_ALL/images/logo.gif").read()

eventlet.spawn(hello, 'abc')
eventlet.spawn(hello, 'xyz')
eventlet.sleep(0)

O / P:<_ MainThread(MainThread,啟動140365670881088)>
2016-08-09 14:04:57.782866
abc你好!!
<_MainThread(MainThread,啟動140365670881088)>
2016-08-09 14:05:02.929903
xyz你好!!

import eventlet
import threading
import datetime
from eventlet.green import urllib2


def hello(name):
    print eventlet.greenthread.getcurrent(), threading.current_thread()
    print datetime.datetime.now()
    print " %s hello !!" % name
    urllib2.urlopen("http://www.google.com/intl/en_ALL/images/logo.gif").read()

pool = eventlet.GreenPool(size=4)
pool.spawn_n(hello, 'pqr')
pool.spawn_n(hello, 'lmn')
pool.waitall()

O / P:<_ MainThread(MainThread,啟動139897149990720)>
2016-08-09 14:05:25.613546
pqr你好!!
<_MainThread(MainThread,啟動139897149990720)>
2016-08-09 14:05:30.699473
你好!

在這兩個版本的代碼中,調用順序進行。

def fun(tag):
  print('{0} begin'.format(tag))
  eventlet.sleep(0.1)  # pretty much the same as running HTTP request and throwing results away
  print('{0} end'.format(tag))

t1 = time.time()
pool.spawn(fun, 'Turtle')
pool.spawn(fun, 'Achilles')
pool.waitall()
tt = time.time() - t1
print('Total time: {0:.2f}'.format(tt))

你會看到與此類似的輸出:

Turtle begin
Achilles begin
Turtle end
Achilles end
Total time: 0.10

這表明函數的執行在IO等待點(休眠)處交錯,這接近於協同並發的定義。 另請注意,總時間不是兩次睡眠的總和,而是最大+基礎設施開銷(在此綜合測試中應該幾乎沒有)。

有問題的代碼無法顯示這一點,因為您在IO之前只有打印(不在Eventlet中創建IO等待),之后沒有。 所以你實際執行的是這樣的:

main: pool.waitall() begin, switch to Eventlet loop
loop: oh, there are greenthreads scheduled to run now, switch to 1
1: print this
1: print that
1: urllib... start network IO, switch to loop
loop: there is another green thread scheduled, switch to 2
2: print this
2: print that
2: urllib... start network IO, switch to Eventlet loop
loop: wait for any event that should wake greenthread,
  suppose that would be thread 1 urllib that is finished first
1: HTTP request finished, thread 1 finished, but no code to prove it
loop: wait for any event...
2: HTTP request finished, thread 2 finished
main: pool.waitall() finished

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM