进程
线程
协程
协程原理:当执行线程遇见io操作时,必须等待线程执行完才能执行别的线程,所以为了提高执行效率,有了协程。使用greenlet可以手动切换线程,当一个greenlet遇见IO,就自动切换到别的greenlet,等到前一个线程IO操作完成在合适的时候切换过来即可。由于IO操作很耗时,经常是程序处于等待状态,手动切换麻烦,有了gevent为我们自动切换协程,就保证,总有greentlet在运行,而不是等待IO,提高了程序执行效率
#不使用greenlet实现切换任务
import time
def work1():
while 1:
print('----work1----')
yield
time.sleep(0.4)
def work2():
while 1:
print('----work2----')
yield
time.sleep(0.4)
def main():
w1=work1()
w2=work2()
while 1:
next(w1)
next(w2)
if __name__ == '__main__':
main()
# 使用greenlet模块实现切换任务
from greenlet import greenlet
import time
def work1():
while 1:
print('---A-----')
gr2.switch()
time.sleep(0.5)
def work2():
while 1:
print('---B-----')
gr1.switch()
time.sleep(0.5)
gr1=greenlet(work1)
gr2=greenlet(work2)
gr1.switch()
# gevent的使用
import gevent
def foo():
print('running in foo')
gevent.sleep(2)
print('come back from bar in to foo')
def bar():
print('running in bar')
gevent.sleep(2)
print('come back from foo in to bar')
gevent.joinall([
gevent.spawn(foo),
gevent.spawn(bar),
])