zoukankan      html  css  js  c++  java
  • gevent模块学习(四)

    gevent.spawn会对传入的子任务集合进行调度,gevent.joinall 方法会阻塞当前程序,除非所有的greenlet都执行完毕,才会退出程序
    公有方法
    gevent.spawn(cls, *args, **kwargs) 创建一个Greenlet对象,其实调用的是Greenlet.spawn(需要from gevent import Greenlet),返回greenlet对象
    gevent.joinall(greenlets, timeout=None, raise_error=False, count=None) 等待所有greenlets全部执行完毕, greenlets为序列,timeout为超时计时器对象,返回执行完毕未出错的的greenlet序列
    greenlet
    g.join() 等待此协程执行完毕后
     
    注意: 多条gevent.spawn(cls, *args, **kwargs).join()语句即使为阻塞调用也不会协程式调用,因为生成的Greenlet对象执行完就消失,所有要实现协程式调用可通过gevent.joinall(greenlets, timeout=None, raise_error=False, count=None)或是赋值到一变量后再对此对象调用.join(),其中一个特殊的方式就是for循环调用将隐式的赋值对象调用,会自动变为协程式运行.
    # coding:utf-8
    
    import gevent
    import random
    
    
    def task(pid):
        gevent.sleep(random.randint(0,2)*0.001)
        print('task %s done'%pid)
    
    
    def synchronous():
        for i in range(1, 10):
            task(i)
    
    
    def asynchronous():
    
        threads = [gevent.spawn(task, i) for i in xrange(10)]
        # print(threads)
        # spawn将task函数封装到greenlet内部线程
        gevent.joinall(threads) # gevent.joinall 阻塞当前流程 并执行所有给定的greenlet 执行完继续往下走
    
    
    print('Synchronous')
    synchronous()
    
    print('Asynchronous')
    asynchronous()
    
    # coding:utf-8
    import gevent.monkey
    gevent.monkey.patch_socket()
    import gevent
    import urllib2
    import json
    
    
    def fetch(pid):
        response = urllib2.urlopen('http://www.baidu.com')
        result = response.read()
        print('Process %s: %s' % (pid, result))
    
    
    
    def synchronous():
        for i in range(1, 10):
            fetch(i)
    
    def asynchronous():
        threads = []
        for i in range(1,10):
            threads.append(gevent.spawn(fetch, i) for i in xrange(10))  # spawn将task函数封装到greenlet内部线程
        gevent.joinall(threads)
    
    
    print('Synchronous')
    synchronous()
    
    print('Asynchronous')
    asynchronous()
    
    #coding:utf-8
    import gevent
    import gevent.monkey
    
    gevent.monkey.patch_all()
    
    # spawn_later函数可接收周期时间及运行函数。
    
    INTERVAL = 10
    
    def schedule(delay, func, *args, **kw_args):
        gevent.spawn_later(1, func, *args, **kw_args)
        gevent.spawn_later(delay, schedule, delay, func, *args, **kw_args)
    
    def test1():
        print "func test1"
    
    def test2():
        print "func test2"
    
    def test3():
        print "test3"
    
    schedule(1,test1)
    schedule(2,test2)
    schedule(3,test3)
    
    while 1:
        gevent.sleep(1)
    
  • 相关阅读:
    nginx限速 原理
    规则引擎 图形界面
    阿里巴巴 规则引擎
    martinfowler Data Guide big data bad things
    Nginx Request URI too large
    linux2.6.30.4内核移植(1)
    根文件系统
    Linux内核配置:定制配置选项
    Linux内核配置:Kconfig
    Linux内核配置:Makefile目标
  • 原文地址:https://www.cnblogs.com/kidl/p/9699321.html
Copyright © 2011-2022 走看看