Python: coroutine, python coroutine

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.