gevent.spawn会对传入的子任务集合进行调度,gevent.joinall 方法会阻塞当前程序,除非所有的greenlet都执行完毕,才会退出程序
公有方法 | |
gevent.spawn(cls, *args, **kwargs) | 创建一个Greenlet对象,其实调用的是Greenlet.spawn(需要from gevent import Greenlet),返回greenlet对象 |
gevent.joinall(greenlets, timeout=None, raise_error=False, count=None) | 等待所有greenlets全部执行完毕, greenlets为序列,timeout为超时计时器对象,返回执行完毕未出错的的greenlet序列 |
greenlet | |
g.join() | 等待此协程执行完毕后 |
注意: 多条gevent.spawn(cls, *args, **kwargs).join()语句即使为阻塞调用也不会协程式调用,因为生成的Greenlet对象执行完就消失,所有要实现协程式调用可通过gevent.joinall(greenlets, timeout=None, raise_error=False, count=None)或是赋值到一变量后再对此对象调用.join(),其中一个特殊的方式就是for循环调用将隐式的赋值对象调用,会自动变为协程式运行.
# coding:utf-8
import gevent
import random
def task(pid):
gevent.sleep(random.randint(0,2)*0.001)
print('task %s done'%pid)
def synchronous():
for i in range(1, 10):
task(i)
def asynchronous():
threads = [gevent.spawn(task, i) for i in xrange(10)]
# print(threads)
# spawn将task函数封装到greenlet内部线程
gevent.joinall(threads) # gevent.joinall 阻塞当前流程 并执行所有给定的greenlet 执行完继续往下走
print('Synchronous')
synchronous()
print('Asynchronous')
asynchronous()
# coding:utf-8
import gevent.monkey
gevent.monkey.patch_socket()
import gevent
import urllib2
import json
def fetch(pid):
response = urllib2.urlopen('http://www.baidu.com')
result = response.read()
print('Process %s: %s' % (pid, result))
def synchronous():
for i in range(1, 10):
fetch(i)
def asynchronous():
threads = []
for i in range(1,10):
threads.append(gevent.spawn(fetch, i) for i in xrange(10)) # spawn将task函数封装到greenlet内部线程
gevent.joinall(threads)
print('Synchronous')
synchronous()
print('Asynchronous')
asynchronous()
#coding:utf-8
import gevent
import gevent.monkey
gevent.monkey.patch_all()
# spawn_later函数可接收周期时间及运行函数。
INTERVAL = 10
def schedule(delay, func, *args, **kw_args):
gevent.spawn_later(1, func, *args, **kw_args)
gevent.spawn_later(delay, schedule, delay, func, *args, **kw_args)
def test1():
print "func test1"
def test2():
print "func test2"
def test3():
print "test3"
schedule(1,test1)
schedule(2,test2)
schedule(3,test3)
while 1:
gevent.sleep(1)