Python greenlet和gevent使用代码示例解析

 更新时间:2020年04月01日 14:26:31   作者:临渊  
这篇文章主要介绍了Python greenlet和gevent使用代码示例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

greenlet示例

greenlet微线程,允许在线程中手动切换

示例1,线程切换

from greenlet import greenlet

def test1(x,y):
  z = gr2.switch(x+y)
  print(z)

def test2(u):
  print(u)
  gr1.switch(42)

gr1 = greenlet(test1)
gr2 = greenlet(test2)
gr1.switch("hello",'world')

gr1和gr2是两个greenlet线程,使用gr1.switch(..)启动gr1,gr1执行test1,切换到gr2,gr2执行test2打印helloworld,然后切换回gr1,z获取

到返回值42,并打印.

执行顺序为:

gr1.switch("hello",'world') -> test1('hello','world')->

gr2.switch('helloword')->test2('helloworld')->print('helloworld')

->gr1.switch(42)->z=42->print(42)

打印结果:

helloworld
42

示例2

from greenlet import greenlet

def eat(name):
  print('%s eat 1' %name)
  g2.switch('egon')
  print('%s eat 2' %name)
  g2.switch()
def play(name):
  print('%s play 1' %name)
  g1.switch()
  print('%s play 2' %name)

g1=greenlet(eat)
g2=greenlet(play)

g1.switch('egon')#可以在第一次switch时传入参数,以后都不需要

g1.switch('egon')#可以在第一次switch时传入参数,以后都不需要

gevent

gevent基于greenlet,遇到IO操作自动切换,IO操作比如网络请求,或使用 gevent.sleep(0)强制切换.

示例1

import gevent

def func1():
  print("start func1")
  gevent.sleep(1)
  print("end func1")

def func2():
   print("start func2")
  gevent.sleep(1)
  print("end func2")

gevent.joinall(
  [
    gevent.spawn(func1),
    gevent.spawn(func2)
  ]
)

执行结果:

start func1
start func2
end func1
end func2
``

示例2: gevent使用monkey对所有系统自带的IO操作打patch

```python
from gevent import monkey;monkey.patch_all()

import gevent
import time
def eat():
  print('eat food 1')
  time.sleep(2) # 会自动的跳转到play
  print('eat food 2')

def play():
  print('play 1')
  time.sleep(1) # 会自动的跳转到eat
  print('play 2')

g1=gevent.spawn(eat)
g2=gevent.spawn(play)
gevent.joinall([g1,g2])
print('end')

执行结果

eat food 1
play 1
play 2
eat food 2
end

示例3,发送请求

from gevent import monkey; monkey.patch_all()
import gevent
import requests

def f(url):
  print('GET: %s' % url)
  resp = requests.get(url)
  data = resp.text
  print('%d bytes received from %s.' % (len(data), url))

gevent.joinall([
    gevent.spawn(f, 'https://www.python.org/'),
    gevent.spawn(f, 'https://www.yahoo.com/'),
    gevent.spawn(f, 'https://github.com/'),
    gevent.spawn(f, 'https://github.com/'),
    gevent.spawn(f, 'https://github.com/'),
    gevent.spawn(f, 'https://github.com/'),
    gevent.spawn(f, 'https://github.com/'),
])

示例4:使用gevent的socket替代系统的socket

import gevent
from gevent import socket

urls = ['www.baidu.com', 'www.163.com', 'www.qq.com']
jobs = [gevent.spawn(socket.gethostbyname, url) for url in urls]
gevent.joinall(jobs, timeout=2)

print([job.value for job in jobs])
或使用patch_socket()
from gevent import monkey; monkey.patch_socket()
import gevent

def f(n):
  for i in range(n):
    print(gevent.getcurrent(), i)
    gevent.sleep(0) # 不加的话不会交替执行
g1 = gevent.spawn(f, 5)
g2 = gevent.spawn(f, 5)
g3 = gevent.spawn(f, 5)
g1.join()
g2.join()
g3.join()

示例5:队列中使用gevent.sleet(0)强制切换到其他线程

import gevent
from gevent.queue import Queue


def func():
  for i in range(10):
    print("int the func")
    q.put(f"test{i}")
    gevent.sleep(0)

def func2():
  for i in range(10):
    print("int the func2")
    res = q.get()
    print("--->",res)

q = Queue()
gevent.joinall(
  [
    gevent.spawn(func2),
    gevent.spawn(func),
  ]
)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Python创建简单的神经网络实例讲解

    Python创建简单的神经网络实例讲解

    在本篇文章里小编给大家整理的是一篇关于如何在Python中创建一个简单的神经网络的相关知识点,有兴趣的朋友们可以参考下。
    2021-01-01
  • 解决os.path.isdir() 判断文件夹却返回false的问题

    解决os.path.isdir() 判断文件夹却返回false的问题

    今天小编就为大家分享一篇解决os.path.isdir() 判断文件夹却返回false的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-11-11
  • python 提取文件的小程序

    python 提取文件的小程序

    在做网站项目时,开发经常要给工程一个升级包,包含本次修改的内容,这个升级包的内容就是tomcat的发布目录下的文件;
    2009-07-07
  • Python中elasticsearch插入和更新数据的实现方法

    Python中elasticsearch插入和更新数据的实现方法

    这篇文章主要介绍了Python中elasticsearch插入和更新数据的实现方法,需要的朋友可以参考下
    2018-04-04
  • Python + Requests + Unittest接口自动化测试实例分析

    Python + Requests + Unittest接口自动化测试实例分析

    这篇文章主要介绍了Python + Requests + Unittest接口自动化测试,结合具体实例形式分析了Python使用Requests与Unittest模块实现接口自动化测试相关操作技巧,需要的朋友可以参考下
    2019-12-12
  • Python用threading实现多线程详解

    Python用threading实现多线程详解

    这篇文章主要给大家介绍了Python用threading实现多线程的方法示例,文中介绍的很详细,对大家具有一定的参考借鉴价值,有需要的朋友们下面来一起学习学习吧。
    2017-02-02
  • Python标准库笔记struct模块的使用

    Python标准库笔记struct模块的使用

    这篇文章主要介绍了Python标准库笔记struct模块的使用,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-02-02
  • 基于TensorBoard中graph模块图结构分析

    基于TensorBoard中graph模块图结构分析

    今天小编就为大家分享一篇基于TensorBoard中graph模块图结构分析,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-02-02
  • Python绘制七段数码管实例代码

    Python绘制七段数码管实例代码

    这篇文章主要介绍了Python绘制七段数码管实例代码,具有一定借鉴价值,需要的朋友可以参考下。
    2017-12-12
  • Django中如何使用sass的方法步骤

    Django中如何使用sass的方法步骤

    这篇文章主要介绍了Django中如何使用sass的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-07-07

最新评论