python:协程

真匿名打脸爱好者 2018-02-08

1,如何实现在两个函数之间的切换?

def func1():
    print(l)
    yield
    print(3)
    yield
def func2():
    g =func1()
    next(g)
    print(2)
    next(g)
    print(4)
func2()

2,协程

import time
from greenlet import greenlet   # 在单线程中切换状态的模块
def eat1():
    print('吃鸡腿1')
    g2.switch()
    time.sleep(5)
    print('吃鸡翅2')
    g2.switch()

def eat2():
    print('吃饺子1')
    g1.switch()
    time.sleep(3)
    print('白切鸡')

g1 = greenlet(eat1)
g2 = greenlet(eat2)
g1.switch()

3,gevent

from gevent import monkey;monkey.patch_all()
import time     # time socket urllib requests
import gevent   # greenlet gevent在切换程序的基础上又实现了规避IO
from threading import current_thread
def func1():
    print(current_thread().name)
    print(123)
    time.sleep(1)
    print(456)

def func2():
    print(current_thread().name)   # dummythread
    print('hahaha')
    time.sleep(1)
    print('10jq')

g1 = gevent.spawn(func1)  # 遇见他认识的io会自动切换的模块
g2 = gevent.spawn(func2)
gevent.joinall([g1,g2])

4,效率对比

from gevent import monkey;monkey.patch_all()
import time     # time socket urllib requests
import gevent   # greenlet gevent在切换程序的基础上又实现了规避IO

def task(args):
    time.sleep(1)
    print(args)

def sync_func():   # 同步
    for i in range(10):
        task(i)

def async_func(): # 异步
    g_l = []
    for i in range(10):
        g_l.append(gevent.spawn(task,i))   # 给写成任务传参数
    gevent.joinall(g_l)

start = time.time()
sync_func()
print(time.time() - start)

start = time.time()
async_func()
print(time.time() - start)

相关推荐

fanhuasijin / 0评论 2019-12-17