Python: coroutine, python coroutine
1. How do I implement switching between two functions?
def func1(): print(l) yield print(3) yielddef func2(): g =func1() next(g) print(2) next(g) print(4)func2()
2. coroutine
Import timefrom greenlet import greenlet # Switch module def eat1 (): print ('eat chicken leg 1') g2.switch () time in a single thread. sleep (5) print ('eat chicken wings 2') g2.switch () def eat2 (): print ('eat dumplings 1') g1.switch () time. sleep (3) print ('white-cut chicken ') g1 = greenlet (eat1) g2 = greenlet (eat2) g1.switch ()
3, gevent
From gevent import monkey; monkey. patch_all () import time # time socket urllib requestsimport gevent # greenlet gevent avoids IOfrom threading import current_threaddef func1 (): print (current_thread () based on the switching program (). name) print (123) time. sleep (1) print (456) def func2 (): print (current_thread (). name) # dummythread print ('hahahaha') time. sleep (1) print ('10jq') g1 = gevent. spawn (func1) # module g2 = gevent that will automatically switch when I meet the io he knows. spawn (func2) gevent. joinall ([g1, g2])
4. Efficiency Comparison
From gevent import monkey; monkey. patch_all () import time # time socket urllib requestsimport gevent # greenlet gevent avoids IOdef task (args): time Based on the switching program. sleep (1) print (args) def sync_func (): # synchronize for I in range (10): task (I) def async_func (): # asynchronous g_l = [] for I in range (10): g_l.append (gevent. spawn (task, I) # upload the gevent parameter to the task. joinall (g_l) start = time. time () sync_func () print (time. time ()-start) start = time. time () async_func () print (time. time ()-start)