deffoo(): print_func_progress() print('Running in foo') gevent.sleep(0) print('Explicit context switch to foo again')
defbar(): print_func_progress() print('Explicit context to bar') gevent.sleep(0) print('Implicit context switch back to bar')
if __name__ == "__main__": gevent.joinall([ gevent.spawn(foo), gevent.spawn(bar), ])
# [1553694796.1719072] Greenlet <Greenlet at 0x10e9a4930: foo> Process 2022 - Thread 4683818432 # Running in foo # [1553694796.171974] Greenlet <Greenlet at 0x10e9a4a60: bar> Process 2022 - Thread 4683818432 # Explicit context to bar # Explicit context switch to foo again # Implicit context switch back to bar
defprint_func_run_time(count, func, **kw): b = timeit.default_timer() for i in range(count): func(**kw) print(func.__name__, 'run {} times used {}s'.format(count, timeit.default_timer() -b ))
deffetch(pid): print('pid {} begin request url', pid) response = requests.get('http://baidu.com') print('pid {} get response status {}', pid, response.status_code)
defsynchronous(): for i in range(0,5): fetch(i)
defasynchronous(): threads = [] for i in range(0,5): threads.append(gevent.spawn(fetch, i)) gevent.joinall(threads)
# Synchronous: # pid {} begin request url 0 # pid {} get response status {} 0 200 # pid {} begin request url 1 # pid {} get response status {} 1 200 # pid {} begin request url 2 # pid {} get response status {} 2 200 # pid {} begin request url 3 # pid {} get response status {} 3 200 # pid {} begin request url 4 # pid {} get response status {} 4 200 # synchronous run 1 times used 0.13507633499102667s # Asynchronous: # pid {} begin request url 0 # pid {} begin request url 1 # pid {} begin request url 2 # pid {} begin request url 3 # pid {} begin request url 4 # pid {} get response status {} 0 200 # pid {} get response status {} 4 200 # pid {} get response status {} 3 200 # pid {} get response status {} 1 200 # pid {} get response status {} 2 200 # asynchronous run 1 times used 0.03902721201302484s