1协程
import gevent
from gevent import monkey
import requests
from bs4 import BeautifulSoup
import threading
monkey.patch_all()
print(threading.current_thread().name) # 打印出当前线程名称
gevent.joinall([gevent.spawn(get_title, i) for i in range(10)])
eg2 greenLet
def foo(message, n):
gevent.sleep(n) print(message)
thread1 = Greenlet.spawn(foo, "Hello", 1) #实例化Greenlet
thread2 = gevent.spawn(foo, "I live!", 2) #实例化gevent,其实也是创建Greenlet实例,只是包装了一下
thread3 = gevent.spawn(lambda x: (x+1), 2) #一个lambda表达式
threads = [thread1, thread2, thread3]
gevent.joinall(threads) #等待所有greenlet完成
#eg3 组
import gevent
from gevent.pool import Group
def talk(msg):
for i in xrange(3):
print(msg)
g1 = gevent.spawn(talk, 'bar')
g2 = gevent.spawn(talk, 'foo')
g3 = gevent.spawn(talk, 'fizz')
group = Group() #保持greenlet实例的组运行,连接到没个项目,在其完成后删除 group.add(g1) group.add(g2) group.join()
group.add(g3) group.join()
爬虫
http://www.shuaiyy.cn/2017/11/04/%E6%8A%80%E6%9C%AF/Gevent%E7%88%AC%E8%99%AB%E4%B8%8E%E5%A4%9A%E7%BA%BF%E7%A8%8B%E7%88%AC%E8%99%AB%E5%AF%B9%E6%AF%94/
指导
http://sdiehl.github.io/gevent-tutorial/