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. hdu 6197 array array array LIS

    正反跑一次LIS,取最大的长度,如果长度大于n-k就满足条件. ac代码: #include <cstdio> #include <cstring> #include < ...

  2. centos mysql数据库问题:ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'mysql'(转)

    问题描述: 安装好数据库MySQL,进入mysql,设置号密码后,退出的时候,利用密码无法进入,直接回车后可进入,无法看到数据库mysql,use mysql返回错误:ERROR 1044 (4200 ...

  3. SQL alchemy

    SQL alchemy介绍 SQL alchemy是orm思想的一个具体实现的产品 orm:对象关系映射思想 Object Relational Mapping 就是将数据库里的资源与面向对象中的类和 ...

  4. 5.创建执行线程的方式之三 :实现Callable 接口

    Callable 接口 一.Java 5.0 在 java.util.concurrent 提供了 一个新的创建执行线程的方式(之前有继承Thread 和 实现Runnable):Callable 接 ...

  5. Ubuntu 系统信息相关命令

    系统信息相关命令 本节内容主要是为了方便通过远程终端维护服务器时,查看服务器上当前 系统日期和时间 / 磁盘空间占用情况 / 程序执行情况 本小结学习的终端命令基本都是查询命令,通过这些命令对系统资源 ...

  6. 虚拟机配置双网卡适配器后(桥接和NAT模式),重新打开后两个适配器的ip都没有了(重启网卡报Job for network.service failed because the control process exited with error code)

    科普双网卡适配器的好处: 我是配了一个桥接模式的网卡和一个NAT模式的网卡,桥接模式,也就是将虚拟机的虚拟网络适配器与主机的物理网络适配器进行交接,虚拟机中的虚拟网络适配器可通过主机中的物理网络适配器 ...

  7. 【SCOI2007】降雨量

    新人求助,降雨量那题本机AC提交WAWAWA…… 原题: 我们常常会说这样的话:“X年是自Y年以来降雨量最多的”.它的含义是X年的降雨量不超过Y年,且对于任意Y<Z<X,Z年的降雨量严格小 ...

  8. linux上构建ftp服务器

    linux上构建ftp服务器 服务器搭建 https://help.aliyun.com/knowledge_detail/60152.html,可以参考这篇博文. 配置文件详解 进入/etc/vsf ...

  9. git ls-files 列出被修改或者被删除的文件

    git ls-files 列出被修改或者被删除的文件 git ls-files -m -d

  10. .npmrc 实用小技巧

    小技巧 因为每次执行 npm adduser 的时候都需要输入用户名.密码和email 很麻烦,我们都可以配置在.npmrc 文件中,在命令行中执行如下脚本 echo -n 'myuser:mypas ...