以下使用gevent模块实现协程,人工控制产生IO阻塞,而不是等某个线程结束后  其他线程竞争式抢资源。注意:gevent模块要从网上找

import gevent,time
def foo():
    print('Running in foo',time.ctime())
    gevent.sleep(2)    #使用gevent来模拟IO阻塞,从而使切换到其他线程
    print('Explicit context switch to foo again',time.ctime())

def bar():
    print('Explicit context to bar',time.ctime())
    gevent.sleep(2)
    print('Implicit context switch back to bar',time.ctime())

gevent.joinall([
    gevent.spawn(foo),
    gevent.spawn(bar)
])

输出:

Running in foo Tue Dec 21 21:49:29 2021
Explicit context to bar Tue Dec 21 21:49:29 2021
Explicit context switch to foo again Tue Dec 21 21:49:31 2021
Implicit context switch back to bar Tue Dec 21 21:49:31 2021

posted on 2021-12-21 22:07  csy113  阅读(18)  评论(0编辑  收藏  举报