from gevent import monkey;monkey.patch_all()
import gevent
import datetime
import time
def eat(name):
print("%s eat first" % name)
time.sleep(3)
print("%s eat second" % name)
def play(name):
print("%s play phone first" % name)
time.sleep(2)
print("%s play phone second" % name)
def run(name):
print("%s run first" % name)
time.sleep(3)
print("%s run second" % name)
普通
start_time = datetime.datetime.now()
eat("don")
play("na")
run("zhe")
end_time = datetime.datetime.now()
print(end_time - start_time)
协程(列表)
job_all = []
g1 = gevent.spawn(eat, "joy")
g2 = gevent.spawn(play, "tok")
g3 = gevent.spawn(run, "together")
job_all.append(g1)
job_all.append(g2)
job_all.append(g3)
print(job_all)
start_time = datetime.datetime.now()
gevent.joinall(job_all)
end_time = datetime.datetime.now()
print("使用协程:", end_time - start_time)
协程(单个)
g1 = gevent.spawn(eat, "joy")
g2 = gevent.spawn(play, "tok")
g3 = gevent.spawn(run, "together")
start_time = datetime.datetime.now()
g1.join()
g2.join()
g3.join()
end_time = datetime.datetime.now()
print("使用协程:", end_time - start_time)