当前位置: 首页 > news >正文

做网站用什么好/成都百度推广联系方式

做网站用什么好,成都百度推广联系方式,如何做网站电话,做a小视频免费观看网站协程在python GIL之下,同一时刻只能有一个线程在运行,那么对于CPU计算密集的程序来说,线程之间的切换开销就成了拖累,而以I/O为瓶颈的程序正是协程所擅长的:Python中的协程经历了很长的一段发展历程。其大概经历了如下…

05bb0732b93cc7b17c9ca02151e24a24.png

协程

在python GIL之下,同一时刻只能有一个线程在运行,那么对于CPU计算密集的程序来说,线程之间的切换开销就成了拖累,而以I/O为瓶颈的程序正是协程所擅长的:

Python中的协程经历了很长的一段发展历程。其大概经历了如下三个阶段:

1.最初的生成器变形yield/send;

2.引入@asyncio.coroutine和yield from;

3.在最近的Python3.5版本中引入async/await关键字。

(1)从yield说起

先看一段普通的计算斐波那契续列的代码def fibs(n):

res = [0] * n

index = 0

a = 0

b = 1

while index 

res[index] = b

a, b = b, a   b

index  = 1

return res

for fib_res in fibs(20):

print(fib_res)

如果我们仅仅是需要拿到斐波那契序列的第n位,或者仅仅是希望依此产生斐波那契序列,那么上面这种传统方式就会比较耗费内存。

这时,yield就派上用场了。def fib(n):

index = 0

a = 0

b = 1

while index 

yield b

a, b = b, a   b

index  = 1

for fib_res in fib(20):

print(fib_res)

当一个函数中包含yield语句时,python会自动将其识别为一个生成器。这时fib(20)并不会真正调用函数体,而是以函数体生成了一个生成器对象实例。

yield在这里可以保留fib函数的计算现场,暂停fib的计算并将b返回。而将fib放入for…in循环中时,每次循环都会调用next(fib(20)),唤醒生成器,执行到下一个yield语句处,直到抛出StopIteration异常。此异常会被for循环捕获,导致跳出循环。

(2) Send来了

从上面的程序中可以看到,目前只有数据从fib(20)中通过yield流向外面的for循环;如果可以向fib(20)发送数据,那不是就可以在Python中实现协程了嘛。

相关推荐:《Python视频教程》

于是,Python中的生成器有了send函数,yield表达式也拥有了返回值。

我们用这个特性,模拟一个慢速斐波那契数列的计算:import time

import random

def stupid_fib(n):

index = 0

a = 0

b = 1

while index 

sleep_cnt = yield b

print('let me think {0} secs'.format(sleep_cnt))

time.sleep(sleep_cnt)

a, b = b, a   b

index  = 1

print('-' * 10   'test yield send'   '-' * 10)

N = 20

sfib = stupid_fib(N)

fib_res = next(sfib)

while True:

print(fib_res)

try:

fib_res = sfib.send(random.uniform(0, 0.5))

except StopIteration:

break

python 进行并发编程

在Python 2的时代,高性能的网络编程主要是使用Twisted、Tornado和Gevent这三个库,但是它们的异步代码相互之间既不兼容也不能移植。

asyncio是Python 3.4版本引入的标准库,直接内置了对异步IO的支持。

asyncio的编程模型就是一个消息循环。我们从asyncio模块中直接获取一个EventLoop的引用,然后把需要执行的协程扔到EventLoop中执行,就实现了异步IO。

Python的在3.4中引入了协程的概念,可是这个还是以生成器对象为基础。

Python 3.5添加了async和await这两个关键字,分别用来替换asyncio.coroutine和yield from。

python3.5则确定了协程的语法。下面将简单介绍asyncio的使用。实现协程的不仅仅是asyncio,tornado和gevent都实现了类似的功能。

(1)协程定义

用asyncio实现Hello world代码如下:import asyncio

@asyncio.coroutine

def hello():

print("Hello world!")

# 异步调用asyncio.sleep(1):

r = yield from asyncio.sleep(1)

print("Hello again!")

# 获取EventLoop:

loop = asyncio.get_event_loop()

# 执行coroutine

loop.run_until_complete(hello())

loop.close()

@asyncio.coroutine把一个generator标记为coroutine类型,然后,我们就把这个coroutine扔到EventLoop中执行。 hello()会首先打印出Hello world!,然后,yield from语法可以让我们方便地调用另一个generator。由于asyncio.sleep()也是一个coroutine,所以线程不会等待asyncio.sleep(),而是直接中断并执行下一个消息循环。当asyncio.sleep()返回时,线程就可以从yield from拿到返回值(此处是None),然后接着执行下一行语句。

把asyncio.sleep(1)看成是一个耗时1秒的IO操作,在此期间,主线程并未等待,而是去执行EventLoop中其他可以执行的coroutine了,因此可以实现并发执行。

我们用Task封装两个coroutine试试:import threading

import asyncio

@asyncio.coroutine

def hello():

print('Hello world! (%s)' % threading.currentThread())

yield from asyncio.sleep(1)

print('Hello again! (%s)' % threading.currentThread())

loop = asyncio.get_event_loop()

tasks = [hello(), hello()]

loop.run_until_complete(asyncio.wait(tasks))

loop.close()

观察执行过程:Hello world! (<_mainthread>)

Hello world! (<_mainthread>)

(暂停约1秒)

Hello again! (<_mainthread>)

Hello again! (<_mainthread>)

由打印的当前线程名称可以看出,两个coroutine是由同一个线程并发执行的。

如果把asyncio.sleep()换成真正的IO操作,则多个coroutine就可以由一个线程并发执行。

asyncio案例实战

我们用asyncio的异步网络连接来获取sina、sohu和163的网站首页:

async_wget.pyimport asyncio

@asyncio.coroutine

def wget(host):

print('wget %s...' % host)

connect = asyncio.open_connection(host, 80)

reader, writer = yield from connect

header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host

writer.write(header.encode('utf-8'))

yield from writer.drain()

while True:

line = yield from reader.readline()

if line == b'\r\n':

break

print('%s header > %s' % (host, line.decode('utf-8').rstrip()))

# Ignore the body, close the socket

writer.close()

loop = asyncio.get_event_loop()

tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]

loop.run_until_complete(asyncio.wait(tasks))

loop.close()

结果信息如下:wget www.sohu.com...

wget www.sina.com.cn...

wget www.163.com...

(等待一段时间)

(打印出sohu的header)

www.sohu.com header > HTTP/1.1 200 OK

www.sohu.com header > Content-Type: text/html

...

(打印出sina的header)

www.sina.com.cn header > HTTP/1.1 200 OK

www.sina.com.cn header > Date: Wed, 20 May 2015 04:56:33 GMT

...

(打印出163的header)

www.163.com header > HTTP/1.0 302 Moved Temporarily

www.163.com header > Server: Cdn Cache Server V2.0

...

可见3个连接由一个线程通过coroutine并发完成。

小结

asyncio提供了完善的异步IO支持;

异步操作需要在coroutine中通过yield from完成;

多个coroutine可以封装成一组Task然后并发执行。

http://www.lbrq.cn/news/1240417.html

相关文章:

  • 医疗器械公司网站建设/百度网页版电脑版
  • wordpress页面导航条/天津外贸seo推广
  • wordpress的站点地址和/网络运营商
  • 在那个网站做推广实用/中央新闻今日要闻
  • 做网站有什么语言好/关键词优化seo排名
  • 做网站如何分页/网站优化流程
  • 网站建设类/南昌网站建设
  • 给你网站你会怎么做的/广告优化师适合女生吗
  • 网站设计论文答辩问题及答案/游戏推广合作
  • 跨境电商平台网站建设广州/baiduseoguide
  • 国外做多媒体展览的网站/株洲发布最新通告
  • 防盗报警网站建设/手机优化管家
  • 网站建设为了什么/优化大师班级
  • 做窗帘网站图片大全/哪个网站做推广效果好
  • 网站内页如何做排名/优化大师百科
  • dw做旅游网站教程/北京网站优化推广方案
  • 网站参考模板/seo项目完整流程
  • 移动网站开发的视频下载/广告联盟app下载
  • 网站建设启动资金预算/seo网站搭建是什么
  • 治多县网站建设公司/新营销模式有哪些
  • 绵阳网站建设开发/seo快速排名软件品牌
  • 乐云网站建设/cms建站
  • 响应式网站建设外文文献/bt种子磁力搜索引擎
  • 漳州做网站含博大网/实时热榜
  • 做ppt介绍网站/网络推广费用
  • 建站网站图片不显示/9 1短视频安装
  • 京东网站难做吗/关键词广告
  • Wordpress 手机网站/网络推广员工作好做吗
  • 一键优化下载安装/江苏seo外包
  • 中教在线3d建模培训/seo推广排名
  • 一键安装RabbitMQ脚本
  • linux2.6 和 unix-v6 源码实验
  • JJWT 核心工具类 Jwts 源码解析
  • Oracle 11g RAC集群部署手册(三)
  • Android使用MediaProjectionManager获取游戏画面和投屏
  • 新手小白如何快速检测IP 的好坏?