简单介绍Python中利用生成器实现的并发编程
作者:goldensun 时间:2022-04-29 00:56:12
我们都知道并发(不是并行)编程目前有四种方式,多进程,多线程,异步,和协程。
多进程编程在python中有类似C的os.fork,当然还有更高层封装的multiprocessing标准库,在之前写过的python高可用程序设计方法中提供了类似nginx中master process和worker process间信号处理的方式,保证了业务进程的退出可以被主进程感知。
多线程编程python中有Thread和threading,在linux下所谓的线程,实际上是LWP轻量级进程,其在内核中具有和进程相同的调度方式,有关LWP,COW(写时拷贝),fork,vfork,clone等的资料较多,这里不再赘述。
异步在linux下主要有三种实现select,poll,epoll,关于异步不是本文的重点。
说协程肯定要说yield,我们先来看一个例子:
#coding=utf-8
import time
import sys
# 生产者
def produce(l):
i=0
while 1:
if i < 5:
l.append(i)
yield i
i=i+1
time.sleep(1)
else:
return
# 消费者
def consume(l):
p = produce(l)
while 1:
try:
p.next()
while len(l) > 0:
print l.pop()
except StopIteration:
sys.exit(0)
l = []
consume(l)
在上面的例子中,当程序执行到produce的yield i时,返回了一个generator,当我们在custom中调用p.next(),程序又返回到produce的yield i继续执行,这样l中又append了元素,然后我们print l.pop(),直到p.next()引发了StopIteration异常。
通过上面的例子我们看到协程的调度对于内核来说是不可见的,协程间是协同调度的,这使得并发量在上万的时候,协程的性能是远高于线程的。
import stackless
import urllib2
def output():
while 1:
url=chan.receive()
print url
f=urllib2.urlopen(url)
#print f.read()
print stackless.getcurrent()
def input():
f=open('url.txt')
l=f.readlines()
for i in l:
chan.send(i)
chan=stackless.channel()
[stackless.tasklet(output)() for i in xrange(10)]
stackless.tasklet(input)()
stackless.run()
关于协程,可以参考greenlet,stackless,gevent,eventlet等的实现。
标签:Python
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
根据Dreamweaver里的ToolTip代码改进的提示框
2008-11-27 12:19:00
mysql: 安装后的目录结构
2011-03-08 09:46:00
python-web根据元素属性进行定位的方法
2021-05-04 04:22:35
如何对python的字典进行排序
2023-01-28 10:47:31
如何基于Python爬取隐秘的角落评论
2022-02-17 05:31:43
![](https://img.aspxhome.com/file/2023/2/87902_0s.jpg)
Python 使用csv库处理CSV文件的方法
2023-03-16 21:37:24
![](https://img.aspxhome.com/file/2023/9/65529_0s.png)
tensorflow实现加载mnist数据集
2022-02-06 06:20:24
![](https://img.aspxhome.com/file/2023/3/105263_0s.jpg)
python实现可变变量名方法详解
2021-04-23 11:42:49
ASP格式化日期的函数(输出13种样式)
2011-07-12 20:22:00
类型转换的小乐趣
2010-11-30 21:37:00
python编写接口测试文档(以豆瓣搜索为例)
2023-09-21 17:39:49
![](https://img.aspxhome.com/file/2023/2/62282_0s.png)
MySQL 数据库语句优化的原则
2010-01-20 10:11:00
微信小程序上传图片功能(附后端代码)
2023-07-24 04:21:40
![](https://img.aspxhome.com/file/2023/9/55969_0s.jpg)
Golang与python线程详解及简单实例
2023-03-13 18:55:25
使用Python 统计文件夹内所有pdf页数的小工具
2022-07-06 23:21:46
![](https://img.aspxhome.com/file/2023/6/77686_0s.png)
Oracle数据库索引的维护
2010-07-26 13:29:00
python 偷懒技巧——使用 keyboard 录制键盘事件
2023-02-08 18:00:03
![](https://img.aspxhome.com/file/2023/9/105339_0s.png)
python实现对服务器脚本敏感信息的加密解密功能
2022-11-07 08:35:11
Python读取stdin方法实例
2022-09-07 19:03:00
![](https://img.aspxhome.com/file/2023/9/86159_0s.png)
线上问题排查之golang使用json进行对象copy
2023-10-06 05:03:23
![](https://img.aspxhome.com/file/2023/9/97169_0s.png)