我使用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
你好!
在两个版本的代码中,调用按顺序进行。
答案 0 :(得分:0)
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