python-eventlet基本使用说明

**客户端示例&说明**

示例代码:

urls = ["http://www.google.com/intl/en_ALL/images/logo.gif",
       "https://wiki.secondlife.com/w/images/secondlife.jpg",
       "http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif"]

import eventlet
from eventlet.green import urllib2

def fetch(url):
    return urllib2.urlopen(url).read()

pool = eventlet.GreenPool()
for body in pool.imap(fetch, urls):
    print "got body", len(body)

     
          from eventlet.green import urllib2
               引入支持并发yield的urllib2实现
               与标准urllib2并无不同,只是使用green socket做通信


          pool = eventlet.GreenPoll()
               建立一个可容纳>1000的green线程池,提供并发支持


          for body in pool.imap(fetch, url)
               imap提供循环内的部分并发运行的能力,并且保证执行结果按执行顺序返回
               注:
                    1.这个并发和顺序返回的特性非常重要
                    2.文档中号称,即使并发量很大,也不会占用太多内存(以GB计)


**服务器端示例&说明**

示例代码

import eventlet


def handle(client):
    while True:
        c = client.recv(1)
        if not c: break
        client.sendall(c)


server = eventlet.listen(('0.0.0.0', 6000))
pool = eventlet.GreenPool(10000)
while True:
    new_sock, address = server.accept()
    pool.spawn_n(handle, new_sock)

          
          pool = eventlet.GreenPool(10000)
               建立一个容纳10000个线程的green线程池
               
          pool.spawn_n(handle, new_sock)
               因为这里,accept循环并不关心处理结果,所以用了spawn_n(而不是spawn)方法


更多稍微实用一点的实例可以参考:http://eventlet.net/doc/examples.html#feed-scraper-example

 

转载于:https://my.oschina.net/kakablue/blog/170528

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值