标签:执行 pre inter coding tps print stop 遇到 sans
协程:
‘‘‘协程‘‘‘
from gevent import monkey;monkey.patch_all()
import gevent
import requests
import threading
all_urls=[
‘https://www.cnblogs.com/yunxintryyoubest/category/1338759.html‘,
‘https://www.cnblogs.com/‘,
‘http://www.baidu.com‘
]
def f(url):
import time
before_time=time.time()
# print(before_time)
response=requests.get(url)
print(response)
after_time=time.time()
# print(after_time)
delay=after_time-before_time
print(‘延迟时间‘,delay)
gevent_list=[]
for i in all_urls:
gevent_list.append(gevent.spawn(f,i))
gevent.joinall(gevent_list)
#协程,里面只要放入列表就可以了,单线程
# gevent.joinall([
# gevent.spawn(f,‘https://www.cnblogs.com/‘),
# gevent.spawn(f, ‘https://www.baidu.com‘),
# gevent.spawn(f, ‘https://www.cnblogs.com/yunxintryyoubest/category/1338759.html‘),
# ])
‘‘‘
gevent内部调用了greenlet,实现了协程,本质上自己不可以完成
协程+IO切换
‘‘‘
基于事件循环的异步非阻塞:
‘‘‘异步‘‘‘
###基于事件循环的异步非阻塞
from twisted.web.client import getPage,defer
from twisted.internet import reactor
url_list=[
‘https://www.cnblogs.com/yunxintryyoubest/category/1338759.html‘,
‘https://www.cnblogs.com/‘,
‘http://www.baidu.com‘
]
defer_list=[]
def call_back(content):
print(content)
for url in url_list:
defered=getPage(bytes(url,encoding=‘utf-8‘))
defered.addCallback(call_back)
defer_list.append(defered)
##把全部的defer加进来列表里面
def defer_stop():
reactor.stop()
defered=defer.DeferredList(defer_list)
defered.addBoth(defer_stop)
reactor.run()
switch:
‘‘‘一个协程内部被switvch切换走了‘‘‘
‘‘‘讲解一下原理:这里面不同的切换,在单线程下面不停的切换
内部调配,事件循环是外部调配‘‘‘
from greenlet import greenlet
def fun1():
print(1)
test2.switch()
print(3)
test2.switch()
##自己内部做切换,遇到io请求,就执行切换
print(5)
‘‘‘携程内部就会进行切换,遇到io请求,就会内部实现切换,自己调用switch
而事件循环是基于外部来调配的‘‘‘
#
def fun2():
print(2)
test1.switch()
print(4)
test1.switch()
test1=greenlet(fun1)
test2=greenlet(fun2)
test1.switch()
‘‘‘会有一个额外的东西进行检测和切换‘‘‘
‘‘‘事件循环是外部来调配的‘‘‘
‘‘‘阻塞的是当上一步完成之后才会执行下一步操作
而非阻塞是当上一步没有完成也会往下走
‘‘‘
标签:执行 pre inter coding tps print stop 遇到 sans
原文地址:https://www.cnblogs.com/yunxintryyoubest/p/9961256.html