##// END OF EJS Templates
testing threading
imanay -
r159:160
parent child
Show More
@@ -0,0 +1,12
1 import threading
2 import datetime
3
4 class ThreadClass(threading.Thread):
5
6 def run(self):
7 now = datetime.datetime.now()
8 print "%s says Hello World at time: %s" % (self.getName(), now)
9
10 for i in range(2):
11 t = ThreadClass()
12 t.start()
@@ -0,0 +1,13
1 import urllib2
2 import time
3
4 hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com",
5 "http://ibm.com", "http://apple.com"]
6
7 start = time.time()
8 #grabs urls of hosts and prints first 1024 bytes of page
9 for host in hosts:
10 url = urllib2.urlopen(host)
11 print url.read(1024)
12
13 print "Elapsed Time: %s" % (time.time() - start) No newline at end of file
@@ -0,0 +1,44
1 #!/usr/bin/env python
2 import Queue
3 import threading
4 import urllib2
5 import time
6
7 hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com",
8 "http://ibm.com", "http://apple.com"]
9
10 queue = Queue.Queue()
11
12 class ThreadUrl(threading.Thread):
13 """Threaded Url Grab"""
14 def __init__(self, queue):
15 threading.Thread.__init__(self)
16 self.queue = queue
17
18 def run(self):
19 while True:
20 #grabs host from queue
21 host = self.queue.get()
22
23 #grabs urls of hosts and prints first 1024 bytes of page
24 url = urllib2.urlopen(host)
25 print url.read(1024)
26
27 #signals to queue job is done
28 self.queue.task_done()
29
30 start = time.time()
31
32 def main():
33 #spawn a pool of threads, and pass them queue instance
34 for i in range(5):
35 t = ThreadUrl(queue)
36 t.setDaemon(True)
37 t.start()
38 #populate queue with data
39 for host in hosts:
40 queue.put(host)
41 queue.join()
42
43 main()
44 print "Elapsed Time: %s" % (time.time() - start) No newline at end of file
General Comments 0
You need to be logged in to leave comments. Login now