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) 相关推荐
efeve 2020-09-14
ericxieforever 2020-09-03
Dimples 2020-06-08
鲁鲁酱 2020-06-02
feishicheng 2020-05-31
paopao00 2020-05-10
georgeandgeorge 2020-05-09
Greatemperor 2020-05-03
jacktangj 2020-04-17
CloudXli 2020-04-07
oXiaoChong 2020-04-07
学习备忘录 2020-02-18
wyqwilliam 2020-02-10
PythonMaker 2020-01-19
ddxygq 2019-12-30
shengge0 2019-12-26
sschencn 2019-12-19
SDUTACM 2019-12-09
千锋 2019-12-07
Laozizuiku 2019-12-04
mayflowers 2019-11-18
wklken的笔记 2019-11-01