yiwai 发表于 2018-8-16 11:23:45

Python 学习笔记 - 协程

  Python里面控制并发,除了多线程和多进程,还可以使用协程(CoRoutine)。他是在一个线程内通过程序员人为的指定来进行切换
  例1:通过switch()可以人为来回切换到另外一个函数;当所有函数执行完毕,最后输出print(10)
#!/usr/bin/env python  
# -*- coding:utf-8 -*-
  
# Author:Alex Li
  
from greenlet import greenlet
  
def test1():
  
    print(12)
  
    gr2.switch()
  
    print(34)
  
    gr2.switch()
  
    print('9')
  
def test2():
  
    print(56)
  
    gr1.switch()
  
    print(78)
  
    gr1.switch()
  
gr1 = greenlet(test1)
  
gr2 = greenlet(test2)
  
gr1.switch()
  
print(10)
  
--------
  
12
  
56
  
34
  
78
  
9
  
10
  例2,除了greenlet模块 我们还可以使用gevent模块
  gevent是第三方库,通过greenlet实现协程,其基本思想是:
  当一个greenlet遇到IO操作时,比如访问网络,就自动切换到其他的greenlet,等到IO操作完成,再在适当的时候切换回来继续执行。由于IO操作非常耗时,经常使程序处于等待状态,有了gevent为我们自动切换协程,就保证总有greenlet在运行,而不是等待IO。
  由于切换是在IO操作时自动完成,所以gevent需要修改Python自带的一些标准库,这一过程在启动时通过monkey patch完成:
  例如:首先导入Gevent和猴子补丁,然后定义一个函数f,gevent.spawn的主要功能是生产greenlet的对象,然后他会内部自动切换,当执行了第一个打印命令之后,因为会阻塞,所以会自动切换到其他的greenlet对象执行操作,之后再切换回来获取数据结果。
#!/usr/bin/env python  
# -*- coding:utf-8 -*-
  

  
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/'),
  
])
  
----------
  
"C:\Program Files\Python3\python.exe" C:/temp/s13day11/day11/s18.py
  
GET: https://www.python.org/
  
GET: https://www.yahoo.com/
  
GET: https://github.com/
  
47413 bytes received from https://www.python.org/.
  
24810 bytes received from https://github.com/.
  
450576 bytes received from https://www.yahoo.com/.


页: [1]
查看完整版本: Python 学习笔记 - 协程