python-gevent模塊(自動切換io的協程)

 

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import  gevent
 
 
def  foo():
 
     print ( "Running in foo" )
     gevent.sleep( 2 )
     print ( "Explicit context switch to foo again" )
 
 
def  bar():
     print ( "Explicit context to bar" )
     gevent.sleep( 1  )
     print ( "Implicit context switch back to bar" )
 
def  func3():
     print ( "running func3" )
     gevent.sleep( 0 ) #遇到io就切換,sleep最長2秒,因此整個程序花費兩秒,若是是串行須要花費3秒
     print ( "running func3 again" )
 
gevent.joinall([
 
     gevent.spawn(foo), #啓動一個協程
     gevent.spawn(bar),
     gevent.spawn(func3)
]
 
)
相關文章
相關標籤/搜索