python:协程

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)

转载于:https://www.cnblogs.com/kakawith/p/8431948.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值