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

所属分类: 脚本专栏 / python 阅读数: 1100
收藏 0 赞 0 分享

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中seaborn包常用图形使用详解

今天小编就为大家分享一篇python中seaborn包常用图形使用详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

numpy:找到指定元素的索引示例

今天小编就为大家分享一篇numpy:找到指定元素的索引示例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

python实现图片上添加图片

这篇文章主要为大家详细介绍了python实现图片上添加图片,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

从numpy数组中取出满足条件的元素示例

今天小编就为大家分享一篇从numpy数组中取出满足条件的元素示例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Python实现图片添加文字

这篇文章主要为大家详细介绍了Python实现图片添加文字,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

python实现在多维数组中挑选符合条件的全部元素

今天小编就为大家分享一篇python实现在多维数组中挑选符合条件的全部元素,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Python如何使用BeautifulSoup爬取网页信息

这篇文章主要介绍了Python如何使用BeautifulSoup爬取网页信息,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
收藏 0 赞 0 分享

浅谈python已知元素,获取元素索引(numpy,pandas)

今天小编就为大家分享一篇浅谈python已知元素,获取元素索引(numpy,pandas),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

numpy ndarray 按条件筛选数组,关联筛选的例子

今天小编就为大家分享一篇numpy ndarray 按条件筛选数组,关联筛选的例子,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Python pickle模块实现对象序列化

这篇文章主要介绍了Python pickle模块实现对象序列化,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多