gevent - 如何並發的執行任務-學習筆記1
「Example
The following example shows how to run tasks concurrently.
>>> import gevent >>> from gevent import socket>>> urls = [www.google.com, www.example.com, www.python.org] >>> jobs = [gevent.spawn(socket.gethostbyname, url) for url in urls] >>> gevent.joinall(jobs, timeout=2) >>> [job.value for job in jobs] [74.125.79.106, 208.77.188.166, 82.94.164.162]
After the jobs have been spawned, gevent.joinall()
waits for them to complete, allowing up to 2 seconds. The results are then collected by checking the value
property. The gevent.socket.gethostbyname()
function has the same interface as the standard socket.gethostbyname()
but it does not block the whole interpreter and thus lets the other greenlets proceed with their requests unhindered.」
在所有的Jobs大量生成之後,gevent.joinall()等待他們去完成,最久等待2s,核查value這個屬性的值手機到結果。gevent.socket.gethostbyname()功能有和標準的socket.gethostbyname()一樣的介面。但是它並不會阻止整個解釋器,因此讓其他的greenlets順暢的處理他們的requests.
Note: 貌似這個spawn()和joinall是重點,但是我怎麼覺得這個執行並不是真正的並行,而是一個執行完執行另外一個,只是循環的去執行了3個任務而已,每個任務不超過2S?需要繼續學習
--待續
推薦閱讀:
※gevent、eventlet、Twisted、Tornado各有什麼區別和優劣?
※Python並發學習筆記:從協程到GEVENT(二)
※gunicorn和uwsgi是怎麼在使用gevent的,gunicorn/uwsgi和gevent?
※為什麼gevent不能配合非純Python的程序一起使用?
TAG:gevent |