Python并发编程-协程

时间:2021-11-11 23:35:18

利用Greenlet模块在多线程之间切换

from greenlet import greenlet
def eat():
    print('eating start')
    g2.switch()
    print('eating end')
    g2.switch()

def play():
    print('playing start')
    g1.switch()
    print('playing end')

g1 = greenlet(eat)
g2 = greenlet(play)
g1.switch()

利用Greenevent模块在协程之间切换

from gevent import monkey;monkey.patch_all()
import gevent
import time

def eat():
    print('eating start')
    # gevent.sleep(1) #一定要有gevent.sleep,传统的time.sleep无效
    #解决方法,引入monkey.patch_all()
    time.sleep(1)
    print('eating end')


def play():
    print('playing start')
    # gevent.sleep(1)
    time.sleep(1)
    print('playing end')

g1 = gevent.spawn(eat) #开启gevent协程
g2 = gevent.spawn(play) #spawn是关键字
g1.join() #必须要join()
g2.join() 

同步和异步的比较

from gevent import monkey;monkey.patch_all()
import gevent
import time

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

def sync():
    for i in range(10):
        task()

def async():
    g_lst = []
    for i in range(10):
        g = gevent.spawn(task)
        g_lst.append(g)
    # for g in g_lst:g.join() #下面这句等同
    gevent.joinall(g_lst)

# sync()
async()

#异步的时候一起打印出来