计算密集型-->需要占用大量的CPU资源-->多进程
IO密集型-->需要网络功能,大量时间都在等待网络数据的到-->多线程、协程
进程、线程的调用由操作系统觉得,携程的调用由开发者自己决定
协程实现
import time
def A():
while True:
print("----A---")
yield #函数里边包含yield 为生成器
time.sleep(0.5)
def B(c):
while True:
print("----B---")
c.next()
time.sleep(0.5)
if __name__=='__main__':
a = A()
B(a)
greenlet
from greenlet import greenlet
import time
def test1():
while True:
print('------A-------')
gr2.switch()
time.sleep(0.5)
def test2():
while True:
print('------B-------')
gr1.switch()
time.sleep(0.5)
gr1 = greenlet(test1)
gr2 = greenlet(test2)
gr1.switch()
gevent
import gevent
def f(n):
for i in range(n):
print(gevent.getcurrent(), i)
gevent.sleep(1)
g1 = gevent.spawn(f, 5)
g2 = gevent.spawn(f, 5)
g3 = gevent.spawn(f, 5)
g1.join()
g2.join()
g3.join()
网友评论