Python协程实现多任务

一、使用gevent实现协程,使用join启动协程。注意此时只能使用gevent.time() 

#from gevent import monkey
import gevent
import time


def f1(n):
    for i in range(n):
        print(gevent.getcurrent(), i)
        # time.sleep(0.5)
        gevent.sleep(0.5)

def f2(n):
    for i in range(n):
        print(gevent.getcurrent(), i)
        # time.sleep(0.5)
        gevent.sleep(0.5)

def f3(n):
    for i in range(n):
        print(gevent.getcurrent(), i)
        # time.sleep(0.5)
        gevent.sleep(0.5)

print("----1---")
g1 = gevent.spawn(f1, 5)
print("----2---")
g2 = gevent.spawn(f2, 5)
print("----3---")
g3 = gevent.spawn(f3, 5)
print("----4---")
g1.join()
g2.join()
g3.join()

二、使用monkey进行协程的启动,此时可以使用time.sleep()

import gevent
import time
from gevent import monkey

monkey.patch_all()


def f1(n):
    for i in range(n):
        print(gevent.getcurrent(), i)
        time.sleep(1)

def f2(n):
    for i in range(n):
        print(gevent.getcurrent(), i)
        time.sleep(1)

def f3(n):
    for i in range(n):
        print(gevent.getcurrent(), i)
        time.sleep(1)

gevent.joinall(
    [
        gevent.spawn(f1,5),
        gevent.spawn(f2,5),
        gevent.spawn(f3,5)
    ]
)

 

你可能感兴趣的:(多任务编程)