同一线程中的两个任务切换

from greenlet import greenlet
def eat(name):
    print('%s eat 1' %name)
    g2.switch('egon')
    print('%s eat 2' %name)
    g2.switch()
def play(name):
    print('%s play 1' %name)
    g1.switch()
    print('%s play 2' %name)
g1=greenlet(eat)
g2=greenlet(play)

g1.switch('egon')

遇到IO阻塞自动切换(推荐)

from gevent import monkey;monkey.patch_all()
import gevent
import time
def eat(name):
    print('%s eat 1'%name)
    time.sleep(2)    #模仿IO阻塞
    print('%s eat 2'%name)
    return 'eat'
def play(name):
    print('%s play 1' % name)
    time.sleep(1)
    print('%s play 2' % name)
    return 'paly'
start = time.time()
g1 = gevent.spawn(eat,'egon')
g2 = gevent.spawn(play,'egon')

gevent.joinall([g1,g2])
print('father',(time.time()-start))
print(g1.value)
print(g2.value)

  


 

posted @ 2017-08-31 16:14  一石数字欠我15w!!!  阅读(344)  评论(0编辑  收藏  举报