python多任务之协程的使用详解

yipeiwu_com7年前Python基础

1|0使用yield完成多任务

import time
def test1():
 while True:
  print("--1--")
  time.sleep(0.5)
  yield None
def test2():
 while True:
  print("--2--")
  time.sleep(0.5)
  yield None
if __name__ == "__main__":
  t1 = test1()
  t2 = test2()
  while True:
    next(t1)
    next(t2)

2|0使用greenlet完成多任务

如果没有安装,则pip install greenlet

from greenlet import greenlet
import time
def test1():
 while True:
  print("---A---")
  gr2.switch()
  time.sleep(0.5)
def test2():
 while True:
  print("---b---")
  gr1.switch()
  time.sleep(0.5)
gr1 = greenlet(test1)
gr2 = greenlet(test2)
gr1.switch()

3|0使用gevent完成多任务

首先使用pip install gevent进行安装

gevent是对greenlet的再次封装,使用起来更加简便,当有耗时操作时会自动切换到其他协程。gevent封装了常用的耗时操作,如thread、socket、time、multiprocessing等模块。

import gevent
import time
from gevent import monkey
# 打补丁,不需要改原来的耗时操作,否则是要使用gevent提供的模块
monkey.patch_all()
def f(n):
 for i in range(n):
  print(gevent.getcurrent(), i)
  # 使用gevent提供的耗时模块
  # gevent.sleep(0.5)
  time.sleep(0.5)
g1 = gevent.spawn(f, 5)
g2 = gevent.spawn(f, 5)
g3 = gevent.spawn(f, 5)
# g1.join()
# g2.join()
# g3.join()
# 一次性添加全部的任务
gevent.joinall([g1,g2,g3])

总结

以上所述是小编给大家介绍的python多任务之协程的使用详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

Python中工作日类库Busines Holiday的介绍与使用

Python中工作日类库Busines Holiday的介绍与使用

引言 大家在日常工作中,经常会碰到类似的场景,需要计算在某个时间段内的工作日以及确定某天是否为工作日,这里的介绍的工具包将很好的解决这个问题。 1. 工具包Business Holid...

树莓派实现移动拍照

驱动树莓派gpio的中间层库函数有wiringPi,BCM2835,以及PRi.GPIO,这里我选择使用Python语言开发的PRi.GPIO。 1、安装RPi.GPIO (1)先安装p...

Python使用Pandas库实现MySQL数据库的读写

Python使用Pandas库实现MySQL数据库的读写

本次分享将介绍如何在Python中使用Pandas库实现MySQL数据库的读写。首先我们需要了解点ORM方面的知识 ORM技术 对象关系映射技术,即ORM(Object-Relatio...

Python实现读取及写入csv文件的方法示例

Python实现读取及写入csv文件的方法示例

本文实例讲述了Python实现读取及写入csv文件的方法。分享给大家供大家参考,具体如下: 新建csvData.csv文件,数据如下: 具体代码如下: # coding:utf-8...

Python中统计函数运行耗时的方法

本文实例讲述了Python中统计函数运行耗时的方法。分享给大家供大家参考。具体实现方法如下: import time def time_me(fn): def _wrapper(...