summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorDenis Bilenko <denis@ag-projects.com>2008-12-10 16:12:33 +0600
committerDenis Bilenko <denis@ag-projects.com>2008-12-10 16:12:33 +0600
commit856b5eecfddfc6894721ccaeadb779f7f2d3fd16 (patch)
tree7ec79c9c8e4eb4a68859b56f6040cb048c006782 /examples
parent2ec37b1d825bc1aecc323f8b7b42a268f838c539 (diff)
downloadeventlet-856b5eecfddfc6894721ccaeadb779f7f2d3fd16.tar.gz
converted examples/connect.py to use coros.spawn_link
Diffstat (limited to 'examples')
-rw-r--r--examples/connect.py50
1 files changed, 36 insertions, 14 deletions
diff --git a/examples/connect.py b/examples/connect.py
index 1a52f60..d38ee9f 100644
--- a/examples/connect.py
+++ b/examples/connect.py
@@ -1,23 +1,45 @@
+"""Spawn multiple greenlet-workers and collect their results.
+
+Demonstrates how to use spawn_link.
+"""
import sys
+import string
+from eventlet.api import sleep
from eventlet.green import socket
-from eventlet.green import time
-from eventlet.api import spawn
+from eventlet.coros import spawn_link
+
+# this example works with both standard eventlet hubs and with twisted-based hub
+# comment out the following line to use standard eventlet hub
+from twisted.internet import reactor
-def client():
- # using domain name directly is of course possible too
- # this is a test to see that dns lookups happen simultaneously too
- ip = socket.gethostbyname('www.google.com')
+def geturl(url):
c = socket.socket()
+ ip = socket.gethostbyname(url)
c.connect((ip, 80))
c.send('GET /\r\n\r\n')
- print c.recv(1024)
+ return c.recv(1024)
+
+def progress_indicator():
+ while True:
+ sys.stderr.write('.')
+ sleep(0.5)
+
+spawn_link(progress_indicator)
+
+urls = ['www.%s.com' % (x*3) for x in string.letters]
+jobs = [spawn_link(geturl, x) for x in urls]
+print 'spawned %s jobs' % len(jobs)
-for x in range(5):
- # note that spawn doesn't switch to new greenlet immediately.
- spawn(client)
+# collect the results from workers, one by one
+for url, job in zip(urls, jobs):
+ sys.stderr.write('%s: ' % url)
+ try:
+ result = job.wait()
+ except Exception, ex: # when using BaseException here and pressing Ctrl-C recv returns None sometimes
+ sys.stderr.write('%s' % ex)
+ else:
+ sys.stderr.write('%s bytes: %s...' % (len(result), repr(result)[:40]))
+ finally:
+ sys.stderr.write('\n')
-# the execution ends with the main greenlet exit (by design), so we need to give control
-# to other greenlets for some time here.
-time.sleep(1)
-sys.stdout.flush()