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时传入参数,以后都不需要

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中greenlet和gevent使用示例的更多相关文章

  1. python中的 uuid 模块使用示例

    此模块提供不可变的 UUID 对象 (类 uuid) 和函数uuid1().uuid3().uuid4().uuid5(), 用于生成在 RFC 4122 中指定版本1.3.4和5UUIDs .如果你 ...

  2. python中关于发邮件的示例

    发送邮件示例代码如下: from WebUtils import ProperitiesLoad from email.mime.text import MIMEText from email.mim ...

  3. python中协程的使用示例

    例子1 把字符串分割为列表 def line_splitter( delimiter = None ): print( 'ready to split' ) result = None while T ...

  4. Python的requests、greenlet和gevent模块在windows下安装

    一.requests模块在windows下安装 Linux系统下requests的安装方法在http://docs.python-requests.org/en/latest/user/install ...

  5. 协程greenlet、gevent

    greenlet为了更好使用协程来完成多任务,python中greenlet模块对其封装,从而使得切换任务变得更加简单安装方式 pip3 install greenlet 示例代码: from gre ...

  6. [Python-MATLAB] 在Python中调用MATLAB的API

    可以参考官方的说明文档: http://cn.mathworks.com/help/matlab/matlab_external/get-started-with-matlab-engine-for- ...

  7. [译]Python中的异步IO:一个完整的演练

    原文:Async IO in Python: A Complete Walkthrough 原文作者: Brad Solomon 原文发布时间:2019年1月16日 翻译:Tacey Wong 翻译时 ...

  8. python中map()和dict()的用法

    map()用法 map()是python的内置函数,会根据提供的函数对指定序列做映射. 语法: map(func, iter, ...) 其中func为一个功能函数,iter表示可迭代参数序列.map ...

  9. python中json模块的使用

    Python自带json模块,它有loads.dumps.load和dump这4个功能,用于Json格式字符串和Python数据类型间进行转换. 一.json.loads() 把Json格式字符串解码 ...

随机推荐

  1. C# SHA512和Base64加解密方法

    /// <summary> /// Get SHA512 Hash From String /// </summary> /// <param name="or ...

  2. jacascript Math (算数)对象

    前言:这是笔者学习之后自己的理解与整理.如果有错误或者疑问的地方,请大家指正,我会持续更新! 实际应用中用的比较多的有:round(); random(); floor(); ceil(); 其次还有 ...

  3. hdu 6208 上一个kmp模板

    #include <cstdio> #include <cstring> #include <iostream> #include <queue> #i ...

  4. (二十)SpringBoot之集成mybatis:使用mybatis注解

    一.使用mybatis注解的集成 1.1 引入maven依赖 <dependencies> <dependency> <groupId>org.springfram ...

  5. Vibe

    在读研和工作之间徘徊了半年,看着一个个好友工作.保研,生活安排得井井有条,我也是时候收拾心情,整装前进了.既然选择了图像,就一定要好好做下去. 今天开始第一个算法,Vibe. ViBe是一种像素级视频 ...

  6. Plugin 免费CSS生成器CssCollector

    下载: 百度云 自己在做Web开发的时候,页面里会有很多样式类,一个个复制到样式表里总感觉很麻烦 网上也没有找到合适的工具,可以一键生成样式表 所以,干脆自己做一个咯~ 案例展示 花了一天时间,CSS ...

  7. moment.js(日期处理类库)的使用

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. ECharts雷达图详细配置说明

    雷达图表配置说明: // 指定图表的配置项和数据 var option = { backgroundColor: 'rgba(204,204,204,0.7 )', // 背景色,默认无背景 rgba ...

  9. OGG 自动重启脚本

    6-20 * * * /oggdata/log/oggautorestart.sh >/oggdata/log/crontab_oggautorestart.log 2>&1 [说 ...

  10. NLP传统基础(1)---BM25算法---计算文档和query相关性

    一.简介:TF-IDF 的改进算法 https://blog.csdn.net/weixin_41090915/article/details/79053584 bm25 是一种用来评价搜索词和文档之 ...