-
Notifications
You must be signed in to change notification settings - Fork 0
/
Fetcher2.py
71 lines (54 loc) · 1.66 KB
/
Fetcher2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env python
# -*- encoding=utf-8 -*-
import threading
from threading import Lock
import urllib2
import time
from Queue import Queue
class Fetcher:
def __init__(self, threads=5):
self.__thread_cnt = threads
self.__threads = []
self.__lock = Lock()
self.q_req = Queue()
self.q_resp = Queue()
self.__running = 0
for i in range(self.__thread_cnt):
new_thread = threading.Thread(target=self.__task)
new_thread.setDaemon(True)
new_thread.start()
self.__threads.append(new_thread)
def __task(self):
while True:
req = self.q_req.get()
print "Req: %s" % (req)
with self.__lock:
self.__running += 1
content = urllib2.urlopen(req).read()
self.q_resp.put((req, content))
with self.__lock:
self.__running -= 1
def push(self, req):
self.q_req.put(req)
def pop(self):
return self.q_resp.get()
def task_left(self):
return self.__running + self.q_resp.qsize() + self.q_req.qsize()
def test():
urls = ["http://www.baidu.com", "http://www.sina.com", "http://www.bing.com"]
reqs = ["%s" % (urls[i%3]) for i in range(15)]
f = Fetcher(20)
s_time = time.time()
for req in reqs:
f.push(req)
while f.task_left():
resp = f.pop()
e_time = time.time()
print "Threads: %fs" % (e_time - s_time)
s_time = time.time()
for req in reqs:
urllib2.urlopen(req).read()
e_time = time.time()
print "Serial: %fs" % (e_time - s_time)
if __name__ == '__main__':
test()