gevent 简单运用

import gevent
import time

def f1(n):
    for i in range(n):
        print(gevent.getcurrent(), i)#获取当前执行的函数
        # print(i,'我来自F1')
        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()

运行结果如下:

----1---
----2---
----3---
----4---
<Greenlet at 0x103a17c48: f1(5)> 0
<Greenlet at 0x103d38148: f2(5)> 0
<Greenlet at 0x103d38248: f3(5)> 0
<Greenlet at 0x103a17c48: f1(5)> 1
<Greenlet at 0x103d38148: f2(5)> 1
<Greenlet at 0x103d38248: f3(5)> 1
<Greenlet at 0x103a17c48: f1(5)> 2
<Greenlet at 0x103d38148: f2(5)> 2
<Greenlet at 0x103d38248: f3(5)> 2
<Greenlet at 0x103a17c48: f1(5)> 3
<Greenlet at 0x103d38148: f2(5)> 3
<Greenlet at 0x103d38248: f3(5)> 3
<Greenlet at 0x103a17c48: f1(5)> 4
<Greenlet at 0x103d38148: f2(5)> 4
<Greenlet at 0x103d38248: f3(5)> 4

也可以:

import gevent
import time

def f1(n):
    for i in range(n):
        print(gevent.getcurrent(), i)#获取当前执行的函数
        # print(i,'我来自F1')
        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)

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

运行结果如下:

<Greenlet at 0x100a7fc48: f1(5)> 0
<Greenlet at 0x100da0148: f2(5)> 0
<Greenlet at 0x100da0248: f3(5)> 0
<Greenlet at 0x100a7fc48: f1(5)> 1
<Greenlet at 0x100da0148: f2(5)> 1
<Greenlet at 0x100da0248: f3(5)> 1
<Greenlet at 0x100a7fc48: f1(5)> 2
<Greenlet at 0x100da0148: f2(5)> 2
<Greenlet at 0x100da0248: f3(5)> 2
<Greenlet at 0x100a7fc48: f1(5)> 3
<Greenlet at 0x100da0148: f2(5)> 3
<Greenlet at 0x100da0248: f3(5)> 3
<Greenlet at 0x100a7fc48: f1(5)> 4
<Greenlet at 0x100da0148: f2(5)> 4
<Greenlet at 0x100da0248: f3(5)> 4

两种方式都可以,第二种方式比较节约代码,建议使用第二种方式

posted @ 2019-07-22 20:41  青春叛逆者  阅读(286)  评论(0编辑  收藏  举报