社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
yield支持下的协程
import time
import queue
def consumer(name):
print("--->starting ...")
while True:
new_baozi = yield # 生成器
print("[%s] is eating baozi %s" % (name, new_baozi))
# time.sleep(1)
# time.sleep(1)
def producer():
# r = con.__next__() # r就是yield
con.__next__()
con2.__next__()
n = 0
while n < 1000:
n += 1
con.send(n) # n发送到consumer里yield里,赋给new_baozi
con2.send(n)
print(" 33[32;1m[producer] 33[0m is making baozi %s" % n)
if __name__ == '__main__':
con = consumer("c1") # 创建生成器对象
con2 = consumer("c2") # 又创建一个生成器对象
p = producer() # 执行producer()函数 p是函数的返回值
genent支持的协程
import gevent
import time
def foo():
print(' 33[31;1mRunning in foo 33[0m', time.ctime())
gevent.sleep(1) # 模拟IO阻塞
print(' 33[31;1mExplicit context switch to foo again 33[0m',time.ctime())
def bar():
print(' 33[32;1mExplicit context to bar 33[0m')
gevent.sleep(2)
print(' 33[32;1mImplicit context switch back to bar 33[0m',time.ctime())
gevent.joinall([ # joinall 把两者连接起来
gevent.spawn(foo), # spawn 生产的意思
gevent.spawn(bar), # 遇到IO阻塞的时候切换
# gevent.spawn(func3),
])
greenlet支持的协程
# -*- coding:utf-8 -*-
from greenlet import greenlet
def test1():
print(12)
gr2.switch()
print(34)
gr2.switch()
def test2():
print(56)
gr1.switch()
print(78)
gr1 = greenlet(test1)
gr2 = greenlet(test2)
gr1.switch() # 谁调用switch()就切换到谁
协程实现一个小爬虫
import gevent
from gevent import monkey
monkey.patch_all() # 监听阻塞
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
from urllib.request import urlopen
import time
def f(url):
print('GET: %s' % url)
resp = urlopen(url)
data = resp.read()
# with open('xiaoahua.html', 'wb') as f:
# f.write(data)
print('%d bytes received from %s.' % (len(data), url))
# l = ['https://www.python.org/','https://www.yahoo.com/', 'https://github.com/']
# start = time.time()
# for url in l:
# f(url)
# print(time.time()-start)
start = time.time()
gevent.joinall([
gevent.spawn(f, 'https://www.python.org/'),
gevent.spawn(f, 'https://www.yahoo.com/'),
gevent.spawn(f, 'https://github.com/'),])
print(time.time()-start)
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!