美文网首页
Python多任务_协程

Python多任务_协程

作者: Lutous | 来源:发表于2020-03-12 17:50 被阅读0次
迭代器Iterator
  • 一个具备了__iter__方法的对象,就是一个可迭代对象
...     def __init__(self):
...             self.container = []
...     def add(self, item):
...             self.container.append(item)
...     def __iter__(self):
...             """返回一个迭代器"""
...             # 我们暂时忽略如何构造一个迭代器对象
...             pass
...
>>> mylist = MyList()
>>> from collections import Iterable
>>> isinstance(mylist, Iterable)
True
  • 创建迭代器
from collections import Iterable
from collections import Iterator


class ClassMate(object):
   def __init__(self):
       self.names = list()
       self.count = 0

   def add(self, name):
       self.names.append(name)

   def __iter__(self):
       """
       若让对象成为可迭代对象,必须实现__iter__方法
       :return: 必须返回迭代器的对象

       迭代器对象必须实现 __iter__,next方法
       """
       return self

   def next(self):
       if self.count < len(self.names):
           res = self.names[self.count]
           self.count += 1
           return res
       else:
           raise StopIteration


classmate = ClassMate()
classmate.add("A")
classmate.add("B")
classmate.add("C")

# 判断是否是迭代对象
print isinstance(classmate, Iterable)
# 判断是否是迭代器
print isinstance(iter(classmate), Iterator)

# next方式实际取对象中的值
print "======================="
print next(iter(classmate))
print "======================="

for name in classmate:
   print name

生成器Generator

生成器是一类特殊的迭代器

#   如果一个函数中有yield语句,这个函数就是一个生成器模板


def fibonacci(count):
   a, b = 0, 1
   current_num = 0
   while current_num < count:
       ret = yield a
       print ">>>>>>>>>>> ret >>>>>>>", ret
       a, b = b, b+a
       current_num += 1


# 如果在调用create_num的时候,发现这个函数中有yield,那么此时不是调用函数,二十创建一个生成器对象
obj = fibonacci(20)
print next(obj)

ret = obj.send(" send value")
print ret
yeild

协程,又称微线程,纤程。英文名Coroutine。

import time


def task_1():
   while True:
       print "-------------task_1-------------"
       time.sleep(0.1)
       yield


def task_2():
   while True:
       print "-------------task_2-------------"
       time.sleep(0.1)
       yield


def main():
   t1 = task_1()
   t2 = task_2()
   # t1 运行遇到yield的时候,返回25行,执行26行,t2执行遇到yield的时候,再次切换到t1中,这样t1,t2交替运行,最终实现了多任务...协程
   while True:
       next(t1)
       next(t2)


if __name__ == '__main__':
   main()

gevent使用
  • 当一个greenlet遇到IO(指的是input output 输入输出,比如网络、文件操作等)操作时,比如访问网络,就自动切换到其他的greenlet,等到IO操作完成,再在适当的时候切换回来继续执行。
  • 由于IO操作非常耗时,经常使程序处于等待状态,有了gevent为我们自动切换协程,就保证总有greenlet在运行,而不是等待IO
  • 安装:pip install gevent
from gevent import monkey
import gevent
import time
monkey.patch_all()


def f1(n):
   for i in xrange(n):
       print gevent.getcurrent(), i
       time.sleep(0.5)


def f2(n):
   for i in xrange(n):
       print gevent.getcurrent(), i
       time.sleep(0.5)


def f3(n):
   for i in xrange(n):
       print gevent.getcurrent(), i
       time.sleep(0.5)


gevent.joinall([
   gevent.spawn(f1, 5),
   gevent.spawn(f2, 5),
   gevent.spawn(f3, 5)
])

相关文章

  • 4-7

    协程 协程,又称微线程,纤程。英文名Coroutine。 协程是啥 协程是python个中另外一种实现多任务的方式...

  • 协程

    协程 协程,又称微线程,纤程。英文名Coroutine。 协程是啥 协程是python个中另外一种实现多任务的方式...

  • 协程——yield

    协程: 协程,又称微线程,纤程。英文名Coroutine。 协程是python个中另外一种实现多任务的方式,只不过...

  • 协程

    协程 协程,又称微线程,纤程。英文名Coroutine。 协程是python个中另外一种实现多任务的方式,只不过比...

  • Python多任务-协程

    协程 协程,又称微线程,纤程。英文名Coroutine。 协程是python个中另外一种实现多任务的方式,只不过比...

  • 多任务-协程

    一、协程的概念 协程,又称微线程,纤程。英文名Coroutine。协程是python中另外一种实现多任务的方式,只...

  • 协程-yield

    协程,又称微线程,纤程。英文名Coroutine。 协程是啥 协程是python个中另外一种实现多任务的方式,只不...

  • 协程-yield

    携程协程,又称微线程,纤程。英文名Coroutine。 协程是python个中另外一种实现多任务的方式,只不过比线...

  • python多任务--协程

    一、前言 协程 协程 ,又称为微线程,它是实现多任务的另一种方式,只不过是比线程更小的执行单元。因为它自带CPU的...

  • Python多任务_协程

    迭代器Iterator 一个具备了__iter__方法的对象,就是一个可迭代对象... def __ini...

网友评论

      本文标题:Python多任务_协程

      本文链接:https://www.haomeiwen.com/subject/ljcvjhtx.html