欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python5协程

程序员文章站 2022-04-09 21:43:50
...
from collections import Iterable
from collections import Iterator
import time
import gevent
#是否可迭代
#print(isinstance([11,22,33], Iterable))


#有__iter__可以迭代,自动调 用__iter__
class Classmate(object):
    def __init__(self):
        self.names = list()

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

    def __iter__(self):
        return ClassIterator(self) #创建实例对象,引用

class ClassIterator(object):
    def __init__(self,classmate):
        self.classmate = classmate
        self.current_num = 0
    def __iter__(self):
        pass
    def __next__(self):
        if self.current_num < len(self.classmate.names):
            ret = self.classmate.names[self.current_num]
            self.current_num += 1
            return ret
        else:
            raise StopIteration


classmate = Classmate()
classmate.append_name("LAO WANG")
classmate.append_name("XIAO LI ")
classmate.append_name("zhang san")
for name in classmate:
    print(name)
    time.sleep(1)

#在一个类里定义
class Classmate(object):
    def __init__(self):
        self.names = list()
        self.current_num = 0

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

    def __iter__(self):
        return self
    def __next__(self):
        if self.current_num < len(self.names):
            ret = self.names[self.current_num]
            self.current_num += 1
            return ret
        else:
            raise StopIteration
classmate = Classmate()
classmate.add("LAO WANG")
classmate.add("XIAO LI ")
classmate.add("zhang san")
for name in classmate:
    print(name)
    time.sleep(1)

#迭代器存储生成数据的方式
class Fibo_obj(object):
    def __init__(self,numbers):
        self.numbers = numbers
        self.a = 0
        self.b = 1
        self.current_num = 0
    def __iter__(self):
        return self
    def __next__(self):
        if self.current_num == 0:
            self.current_num += 1
            return self.a
        elif self.current_num < self.numbers:
            self.a, self.b = self.b, self.a + self.b
            self.current_num += 1
            return self.a

        else:
            raise StopIteration
FIBO = Fibo_obj(20)
for i,num in enumerate(FIBO):
    print(i, num)
#生成器,特殊的迭代器,当前迭代到的状态需要自己记录
def fibo(numbers):
    a, b = 0, 1
    current_num = 0
    while current_num < numbers:
        yield a
        a, b = b, a+b
        current_num += 1
    return "Over"
test1 = fibo(25)
test2 = fibo(25)

print(test1)
for i,num in enumerate(test1):
    print(i,num)

while True:
    try:
       ret = next(test2)

       print(ret)
    except Exception as ret:
        print(ret.value)
        break
#send传递参数
def create_num(all_num):
    a, b = 0, 1
    current_num = 0
    while current_num < all_num:
        ret = yield a
        print("<<<ret>>>",ret)
        a, b = b, a+b
        current_num += 1
obj = create_num(10)
ret = next(obj)
print(ret)
ret = obj.send(3)
print(ret)

ret = next(obj)
print(ret)
ret = obj.send(3)
print(ret)
#多任务

def task1():
    print(1)
    time.sleep(1)
    yield
def task2():
    print(2)
    time.sleep(1)
    yield 
while True:
    next(task1())
    next(task2())
#greenlet单线程实现多任务
from greenlet import greenlet
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()
#携程依赖于资源,切换资源很快,相当于调用函数
#协程利用延时的时间
def f1(n):
    for i in range(n):
        print(gevent.getcurrent(), i)
        gevent.sleep(0.5)
def f2(n):
    for i in range(n):
        print(gevent.getcurrent(), i)
        gevent.sleep(0.5)
def f3(n):
    for i in range(n):
        print(gevent.getcurrent(), i)
        gevent.sleep(0.5)
print("----1----")
g1 = gevent.spawn(f1, 5)
print("----2----")
g2 = gevent.spawn(f2, 5)
print("----3----")
g3 = gevent.spawn(f3, 5)

g1.join()
g2.join()
g3.join()